home *** CD-ROM | disk | FTP | other *** search
/ PC go! 2008 October / PCgo 2008-10 (DVD).iso / interface / contents / vollversionen_6617 / 21733 / files / xulrunner / components / nsExtensionManager.js < prev    next >
Encoding:
Text File  |  2008-08-20  |  323.8 KB  |  8,768 lines

  1. /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /*
  3. //@line 44 "e:\builds\tinderbox\XR-Trunk\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  4. */
  5.  
  6. //
  7. // TODO:
  8. // - better logging
  9. //
  10.  
  11. const Cc = Components.classes;
  12. const Ci = Components.interfaces;
  13. const Cr = Components.results;
  14.  
  15. Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
  16.  
  17. const PREF_EM_CHECK_COMPATIBILITY     = "extensions.checkCompatibility";
  18. const PREF_EM_CHECK_UPDATE_SECURITY   = "extensions.checkUpdateSecurity";
  19. const PREF_EM_LAST_APP_VERSION        = "extensions.lastAppVersion";
  20. const PREF_EM_ENABLED_ITEMS           = "extensions.enabledItems";
  21. const PREF_UPDATE_COUNT               = "extensions.update.count";
  22. const PREF_UPDATE_DEFAULT_URL         = "extensions.update.url";
  23. const PREF_EM_NEW_ADDONS_LIST         = "extensions.newAddons";
  24. const PREF_EM_IGNOREMTIMECHANGES      = "extensions.ignoreMTimeChanges";
  25. const PREF_EM_DISABLEDOBSOLETE        = "extensions.disabledObsolete";
  26. const PREF_EM_EXTENSION_FORMAT        = "extensions.%UUID%.";
  27. const PREF_EM_ITEM_UPDATE_ENABLED     = "extensions.%UUID%.update.enabled";
  28. const PREF_EM_UPDATE_ENABLED          = "extensions.update.enabled";
  29. const PREF_EM_ITEM_UPDATE_URL         = "extensions.%UUID%.update.url";
  30. const PREF_EM_DSS_ENABLED             = "extensions.dss.enabled";
  31. const PREF_DSS_SWITCHPENDING          = "extensions.dss.switchPending";
  32. const PREF_DSS_SKIN_TO_SELECT         = "extensions.lastSelectedSkin";
  33. const PREF_GENERAL_SKINS_SELECTEDSKIN = "general.skins.selectedSkin";
  34. const PREF_EM_LOGGING_ENABLED         = "extensions.logging.enabled";
  35. const PREF_EM_UPDATE_INTERVAL         = "extensions.update.interval";
  36. const PREF_UPDATE_NOTIFYUSER          = "extensions.update.notifyUser";
  37. const PREF_MATCH_OS_LOCALE            = "intl.locale.matchOS";
  38. const PREF_SELECTED_LOCALE            = "general.useragent.locale";
  39.  
  40. const DIR_EXTENSIONS                  = "extensions";
  41. const DIR_CHROME                      = "chrome";
  42. const DIR_STAGE                       = "staged-xpis";
  43. const FILE_EXTENSIONS                 = "extensions.rdf";
  44. const FILE_EXTENSION_MANIFEST         = "extensions.ini";
  45. const FILE_EXTENSIONS_STARTUP_CACHE   = "extensions.cache";
  46. const FILE_EXTENSIONS_LOG             = "extensions.log";
  47. const FILE_AUTOREG                    = ".autoreg";
  48. const FILE_INSTALL_MANIFEST           = "install.rdf";
  49. const FILE_CONTENTS_MANIFEST          = "contents.rdf";
  50. const FILE_CHROME_MANIFEST            = "chrome.manifest";
  51.  
  52. const UNKNOWN_XPCOM_ABI               = "unknownABI";
  53.  
  54. const FILE_DEFAULT_THEME_JAR          = "classic.jar";
  55. const TOOLKIT_ID                      = "toolkit@mozilla.org"
  56.  
  57. const KEY_PROFILEDIR                  = "ProfD";
  58. const KEY_PROFILEDS                   = "ProfDS";
  59. const KEY_APPDIR                      = "XCurProcD";
  60. const KEY_TEMPDIR                     = "TmpD";
  61.  
  62. const EM_ACTION_REQUESTED_TOPIC       = "em-action-requested";
  63. const EM_ITEM_INSTALLED               = "item-installed";
  64. const EM_ITEM_UPGRADED                = "item-upgraded";
  65. const EM_ITEM_UNINSTALLED             = "item-uninstalled";
  66. const EM_ITEM_ENABLED                 = "item-enabled";
  67. const EM_ITEM_DISABLED                = "item-disabled";
  68. const EM_ITEM_CANCEL                  = "item-cancel-action";
  69.  
  70. const OP_NONE                         = "";
  71. const OP_NEEDS_INSTALL                = "needs-install";
  72. const OP_NEEDS_UPGRADE                = "needs-upgrade";
  73. const OP_NEEDS_UNINSTALL              = "needs-uninstall";
  74. const OP_NEEDS_ENABLE                 = "needs-enable";
  75. const OP_NEEDS_DISABLE                = "needs-disable";
  76.  
  77. const KEY_APP_PROFILE                 = "app-profile";
  78. const KEY_APP_GLOBAL                  = "app-global";
  79. const KEY_APP_SYSTEM_LOCAL            = "app-system-local";
  80. const KEY_APP_SYSTEM_SHARE            = "app-system-share";
  81. const KEY_APP_SYSTEM_USER             = "app-system-user";
  82.  
  83. const CATEGORY_INSTALL_LOCATIONS      = "extension-install-locations";
  84. const CATEGORY_UPDATE_PARAMS          = "extension-update-params";
  85.  
  86. const PREFIX_NS_EM                    = "http://www.mozilla.org/2004/em-rdf#";
  87. const PREFIX_NS_CHROME                = "http://www.mozilla.org/rdf/chrome#";
  88. const PREFIX_ITEM_URI                 = "urn:mozilla:item:";
  89. const PREFIX_EXTENSION                = "urn:mozilla:extension:";
  90. const PREFIX_THEME                    = "urn:mozilla:theme:";
  91. const RDFURI_INSTALL_MANIFEST_ROOT    = "urn:mozilla:install-manifest";
  92. const RDFURI_ITEM_ROOT                = "urn:mozilla:item:root"
  93. const RDFURI_DEFAULT_THEME            = "urn:mozilla:item:{972ce4c6-7e08-4474-a285-3208198ce6fd}";
  94. const XMLURI_PARSE_ERROR              = "http://www.mozilla.org/newlayout/xml/parsererror.xml"
  95.  
  96. const URI_GENERIC_ICON_XPINSTALL      = "chrome://mozapps/skin/xpinstall/xpinstallItemGeneric.png";
  97. const URI_GENERIC_ICON_THEME          = "chrome://mozapps/skin/extensions/themeGeneric.png";
  98. const URI_XPINSTALL_CONFIRM_DIALOG    = "chrome://mozapps/content/xpinstall/xpinstallConfirm.xul";
  99. const URI_EXTENSIONS_PROPERTIES       = "chrome://mozapps/locale/extensions/extensions.properties";
  100. const URI_BRAND_PROPERTIES            = "chrome://branding/locale/brand.properties";
  101. const URI_DOWNLOADS_PROPERTIES        = "chrome://mozapps/locale/downloads/downloads.properties";
  102. const URI_EXTENSION_UPDATE_DIALOG     = "chrome://mozapps/content/extensions/update.xul";
  103. const URI_EXTENSION_LIST_DIALOG       = "chrome://mozapps/content/extensions/list.xul";
  104.  
  105. const INSTALLERROR_SUCCESS               = 0;
  106. const INSTALLERROR_INVALID_VERSION       = -1;
  107. const INSTALLERROR_INVALID_GUID          = -2;
  108. const INSTALLERROR_INCOMPATIBLE_VERSION  = -3;
  109. const INSTALLERROR_PHONED_HOME           = -4;
  110. const INSTALLERROR_INCOMPATIBLE_PLATFORM = -5;
  111. const INSTALLERROR_BLOCKLISTED           = -6;
  112. const INSTALLERROR_INSECURE_UPDATE       = -7;
  113. const INSTALLERROR_INVALID_MANIFEST      = -8;
  114. const INSTALLERROR_RESTRICTED            = -9;
  115.  
  116. const MODE_RDONLY   = 0x01;
  117. const MODE_WRONLY   = 0x02;
  118. const MODE_CREATE   = 0x08;
  119. const MODE_APPEND   = 0x10;
  120. const MODE_TRUNCATE = 0x20;
  121.  
  122. const PERMS_FILE      = 0644;
  123. const PERMS_DIRECTORY = 0755;
  124.  
  125. var gApp  = null;
  126. var gPref = null;
  127. var gRDF  = null;
  128. var gOS   = null;
  129. var gBlocklist            = null;
  130. var gXPCOMABI             = null;
  131. var gOSTarget             = null;
  132. var gConsole              = null;
  133. var gInstallManifestRoot  = null;
  134. var gVersionChecker       = null;
  135. var gLoggingEnabled       = null;
  136. var gCheckCompatibility   = true;
  137. var gCheckUpdateSecurity  = true;
  138. var gLocale               = "en-US";
  139. var gFirstRun             = false;
  140.  
  141. /**
  142.  * Valid GUIDs fit this pattern.
  143.  */
  144. var gIDTest = /^(\{[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}|[a-z0-9-\._]*\@[a-z0-9-\._]+)$/i;
  145.  
  146. // shared code for suppressing bad cert dialogs
  147. //@line 40 "e:\builds\tinderbox\XR-Trunk\WINNT_5.2_Depend\mozilla\toolkit\mozapps\shared\src\badCertHandler.js"
  148.  
  149. /**
  150.  * Only allow built-in certs for HTTPS connections.  See bug 340198.
  151.  */
  152. function checkCert(channel) {
  153.   if (!channel.originalURI.schemeIs("https"))  // bypass
  154.     return;
  155.  
  156.   const Ci = Components.interfaces;  
  157.   var cert =
  158.       channel.securityInfo.QueryInterface(Ci.nsISSLStatusProvider).
  159.       SSLStatus.QueryInterface(Ci.nsISSLStatus).serverCert;
  160.  
  161.   var issuer = cert.issuer;
  162.   while (issuer && !cert.equals(issuer)) {
  163.     cert = issuer;
  164.     issuer = cert.issuer;
  165.   }
  166.  
  167.   if (!issuer || issuer.tokenName != "Builtin Object Token")
  168.     throw "cert issuer is not built-in";
  169. }
  170.  
  171. /**
  172.  * This class implements nsIBadCertListener.  It's job is to prevent "bad cert"
  173.  * security dialogs from being shown to the user.  It is better to simply fail
  174.  * if the certificate is bad. See bug 304286.
  175.  */
  176. function BadCertHandler() {
  177. }
  178. BadCertHandler.prototype = {
  179.  
  180.   // nsIChannelEventSink
  181.   onChannelRedirect: function(oldChannel, newChannel, flags) {
  182.     // make sure the certificate of the old channel checks out before we follow
  183.     // a redirect from it.  See bug 340198.
  184.     checkCert(oldChannel);
  185.   },
  186.  
  187.   // Suppress any certificate errors
  188.   notifyCertProblem: function(socketInfo, status, targetSite) {
  189.     return true;
  190.   },
  191.  
  192.   // Suppress any ssl errors
  193.   notifySSLError: function(socketInfo, error, targetSite) {
  194.     return true;
  195.   },
  196.  
  197.   // nsIInterfaceRequestor
  198.   getInterface: function(iid) {
  199.     return this.QueryInterface(iid);
  200.   },
  201.  
  202.   // nsISupports
  203.   QueryInterface: function(iid) {
  204.     if (!iid.equals(Components.interfaces.nsIChannelEventSink) &&
  205.         !iid.equals(Components.interfaces.nsIBadCertListener2) &&
  206.         !iid.equals(Components.interfaces.nsISSLErrorListener) &&
  207.         !iid.equals(Components.interfaces.nsIInterfaceRequestor) &&
  208.         !iid.equals(Components.interfaces.nsISupports))
  209.       throw Components.results.NS_ERROR_NO_INTERFACE;
  210.     return this;
  211.   }
  212. };
  213. //@line 188 "e:\builds\tinderbox\XR-Trunk\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  214.  
  215. /**
  216.  * Creates a Version Checker object.
  217.  * @returns A handle to the global Version Checker service.
  218.  */
  219. function getVersionChecker() {
  220.   if (!gVersionChecker) {
  221.     gVersionChecker = Cc["@mozilla.org/xpcom/version-comparator;1"].
  222.                       getService(Ci.nsIVersionComparator);
  223.   }
  224.   return gVersionChecker;
  225. }
  226.  
  227. var BundleManager = {
  228.   /**
  229.   * Creates and returns a String Bundle at the specified URI
  230.   * @param   bundleURI
  231.   *          The URI of the bundle to load
  232.   * @returns A nsIStringBundle which was retrieved.
  233.   */
  234.   getBundle: function(bundleURI) {
  235.     var sbs = Cc["@mozilla.org/intl/stringbundle;1"].
  236.               getService(Ci.nsIStringBundleService);
  237.     return sbs.createBundle(bundleURI);
  238.   },
  239.  
  240.   _appName: "",
  241.  
  242.   /**
  243.    * The Application's display name.
  244.    */
  245.   get appName() {
  246.     if (!this._appName) {
  247.       var brandBundle = this.getBundle(URI_BRAND_PROPERTIES)
  248.       this._appName = brandBundle.GetStringFromName("brandShortName");
  249.     }
  250.     return this._appName;
  251.   }
  252. };
  253.  
  254. ///////////////////////////////////////////////////////////////////////////////
  255. //
  256. // Utility Functions
  257. //
  258. function EM_NS(property) {
  259.   return PREFIX_NS_EM + property;
  260. }
  261.  
  262. function CHROME_NS(property) {
  263.   return PREFIX_NS_CHROME + property;
  264. }
  265.  
  266. function EM_R(property) {
  267.   return gRDF.GetResource(EM_NS(property));
  268. }
  269.  
  270. function EM_L(literal) {
  271.   return gRDF.GetLiteral(literal);
  272. }
  273.  
  274. function EM_I(integer) {
  275.   return gRDF.GetIntLiteral(integer);
  276. }
  277.  
  278. function EM_D(integer) {
  279.   return gRDF.GetDateLiteral(integer);
  280. }
  281.  
  282. /**
  283.  * Gets a preference value, handling the case where there is no default.
  284.  * @param   func
  285.  *          The name of the preference function to call, on nsIPrefBranch
  286.  * @param   preference
  287.  *          The name of the preference
  288.  * @param   defaultValue
  289.  *          The default value to return in the event the preference has
  290.  *          no setting
  291.  * @returns The value of the preference, or undefined if there was no
  292.  *          user or default value.
  293.  */
  294. function getPref(func, preference, defaultValue) {
  295.   try {
  296.     return gPref[func](preference);
  297.   }
  298.   catch (e) {
  299.   }
  300.   return defaultValue;
  301. }
  302.  
  303. /**
  304.  * Initializes a RDF Container at a URI in a datasource.
  305.  * @param   datasource
  306.  *          The datasource the container is in
  307.  * @param   root
  308.  *          The RDF Resource which is the root of the container.
  309.  * @returns The nsIRDFContainer, initialized at the root.
  310.  */
  311. function getContainer(datasource, root) {
  312.   var ctr = Cc["@mozilla.org/rdf/container;1"].
  313.             createInstance(Ci.nsIRDFContainer);
  314.   ctr.Init(datasource, root);
  315.   return ctr;
  316. }
  317.  
  318. /**
  319.  * Gets a RDF Resource for item with the given ID
  320.  * @param   id
  321.  *          The GUID of the item to construct a RDF resource to the
  322.  *          active item for
  323.  * @returns The RDF Resource to the Active item.
  324.  */
  325. function getResourceForID(id) {
  326.   return gRDF.GetResource(PREFIX_ITEM_URI + id);
  327. }
  328.  
  329. /**
  330.  * Construct a nsIUpdateItem with the supplied metadata
  331.  * ...
  332.  */
  333. function makeItem(id, version, locationKey, minVersion, maxVersion, name,
  334.                   updateURL, updateHash, iconURL, updateRDF, updateKey, type, 
  335.                   targetAppID) {
  336.   var item = new UpdateItem();
  337.   item.init(id, version, locationKey, minVersion, maxVersion, name,
  338.             updateURL, updateHash, iconURL, updateRDF, updateKey, type,
  339.             targetAppID);
  340.   return item;
  341. }
  342.  
  343. /**
  344.  * Gets the specified directory at the specified hierarchy under a
  345.  * Directory Service key.
  346.  * @param   key
  347.  *          The Directory Service Key to start from
  348.  * @param   pathArray
  349.  *          An array of path components to locate beneath the directory
  350.  *          specified by |key|
  351.  * @return  nsIFile object for the location specified. If the directory
  352.  *          requested does not exist, it is created, along with any
  353.  *          parent directories that need to be created.
  354.  */
  355. function getDir(key, pathArray) {
  356.   return getDirInternal(key, pathArray, true);
  357. }
  358.  
  359. /**
  360.  * Gets the specified directory at the specified hierarchy under a
  361.  * Directory Service key.
  362.  * @param   key
  363.  *          The Directory Service Key to start from
  364.  * @param   pathArray
  365.  *          An array of path components to locate beneath the directory
  366.  *          specified by |key|
  367.  * @return  nsIFile object for the location specified. If the directory
  368.  *          requested does not exist, it is NOT created.
  369.  */
  370. function getDirNoCreate(key, pathArray) {
  371.   return getDirInternal(key, pathArray, false);
  372. }
  373.  
  374. /**
  375.  * Gets the specified directory at the specified hierarchy under a
  376.  * Directory Service key.
  377.  * @param   key
  378.  *          The Directory Service Key to start from
  379.  * @param   pathArray
  380.  *          An array of path components to locate beneath the directory
  381.  *          specified by |key|
  382.  * @param   shouldCreate
  383.  *          true if the directory hierarchy specified in |pathArray|
  384.  *          should be created if it does not exist,
  385.  *          false otherwise.
  386.  * @return  nsIFile object for the location specified.
  387.  */
  388. function getDirInternal(key, pathArray, shouldCreate) {
  389.   var fileLocator = Cc["@mozilla.org/file/directory_service;1"].
  390.                     getService(Ci.nsIProperties);
  391.   var dir = fileLocator.get(key, Ci.nsILocalFile);
  392.   for (var i = 0; i < pathArray.length; ++i) {
  393.     dir.append(pathArray[i]);
  394.     if (shouldCreate && !dir.exists())
  395.       dir.create(Ci.nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  396.   }
  397.   dir.followLinks = false;
  398.   return dir;
  399. }
  400.  
  401. /**
  402.  * Gets the file at the specified hierarchy under a Directory Service key.
  403.  * @param   key
  404.  *          The Directory Service Key to start from
  405.  * @param   pathArray
  406.  *          An array of path components to locate beneath the directory
  407.  *          specified by |key|. The last item in this array must be the
  408.  *          leaf name of a file.
  409.  * @return  nsIFile object for the file specified. The file is NOT created
  410.  *          if it does not exist, however all required directories along
  411.  *          the way are.
  412.  */
  413. function getFile(key, pathArray) {
  414.   var file = getDir(key, pathArray.slice(0, -1));
  415.   file.append(pathArray[pathArray.length - 1]);
  416.   return file;
  417. }
  418.  
  419. /**
  420.  * Gets the descriptor of a directory as a relative path to common base
  421.  * directories (profile, user home, app install dir, etc).
  422.  *
  423.  * @param   itemLocation
  424.  *          The nsILocalFile representing the item's directory.
  425.  * @param   installLocation the nsIInstallLocation for this item
  426.  */
  427. function getDescriptorFromFile(itemLocation, installLocation) {
  428.   var baseDir = installLocation.location;
  429.  
  430.   if (baseDir && baseDir.contains(itemLocation, true)) {
  431.     return "rel%" + itemLocation.getRelativeDescriptor(baseDir);
  432.   }
  433.  
  434.   return "abs%" + itemLocation.persistentDescriptor;
  435. }
  436.  
  437. function getAbsoluteDescriptor(itemLocation) {
  438.   return itemLocation.persistentDescriptor;
  439. }
  440.  
  441. /**
  442.  * Initializes a Local File object based on a descriptor
  443.  * provided by "getDescriptorFromFile".
  444.  *
  445.  * @param   descriptor
  446.  *          The descriptor that locates the directory
  447.  * @param   installLocation
  448.  *          The nsIInstallLocation object for this item.
  449.  * @returns The nsILocalFile object representing the location of the item
  450.  */
  451. function getFileFromDescriptor(descriptor, installLocation) {
  452.   var location = Cc["@mozilla.org/file/local;1"].
  453.                  createInstance(Ci.nsILocalFile);
  454.  
  455.   var m = descriptor.match(/^(abs|rel)\%(.*)$/);
  456.   if (!m)
  457.     throw Cr.NS_ERROR_INVALID_ARG;
  458.  
  459.   if (m[1] == "rel") {
  460.     location.setRelativeDescriptor(installLocation.location, m[2]);
  461.   }
  462.   else {
  463.     location.persistentDescriptor = m[2];
  464.   }
  465.  
  466.   return location;
  467. }
  468.  
  469. /**
  470.  * Determines if a file is an item package - either a XPI or a JAR file.
  471.  * @param   file
  472.  *          The file to check
  473.  * @returns true if the file is an item package, false otherwise.
  474.  */
  475. function fileIsItemPackage(file) {
  476.   var fileURL = getURIFromFile(file);
  477.   if (fileURL instanceof Ci.nsIURL)
  478.     var extension = fileURL.fileExtension.toLowerCase();
  479.   return extension == "xpi" || extension == "jar";
  480. }
  481.  
  482. /**
  483.  * Opens a safe file output stream for writing.
  484.  * @param   file
  485.  *          The file to write to.
  486.  * @param   modeFlags
  487.  *          (optional) File open flags. Can be undefined.
  488.  * @returns nsIFileOutputStream to write to.
  489.  */
  490. function openSafeFileOutputStream(file, modeFlags) {
  491.   var fos = Cc["@mozilla.org/network/safe-file-output-stream;1"].
  492.             createInstance(Ci.nsIFileOutputStream);
  493.   if (modeFlags === undefined)
  494.     modeFlags = MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE;
  495.   if (!file.exists())
  496.     file.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  497.   fos.init(file, modeFlags, PERMS_FILE, 0);
  498.   return fos;
  499. }
  500.  
  501. /**
  502.  * Closes a safe file output stream.
  503.  * @param   stream
  504.  *          The stream to close.
  505.  */
  506. function closeSafeFileOutputStream(stream) {
  507.   if (stream instanceof Ci.nsISafeOutputStream)
  508.     stream.finish();
  509.   else
  510.     stream.close();
  511. }
  512.  
  513. /**
  514.  * Deletes a directory and its children. First it tries nsIFile::Remove(true).
  515.  * If that fails it will fall back to recursing, setting the appropriate
  516.  * permissions, and deleting the current entry. This is needed for when we have
  517.  * rights to delete a directory but there are entries that have a read-only
  518.  * attribute (e.g. a copy restore from a read-only CD, etc.)
  519.  * @param   dir
  520.  *          A nsIFile for the directory to be deleted
  521.  */
  522. function removeDirRecursive(dir) {
  523.   try {
  524.     dir.remove(true);
  525.     return;
  526.   }
  527.   catch (e) {
  528.   }
  529.  
  530.   var dirEntries = dir.directoryEntries;
  531.   while (dirEntries.hasMoreElements()) {
  532.     var entry = dirEntries.getNext().QueryInterface(Ci.nsIFile);
  533.  
  534.     if (entry.isDirectory()) {
  535.       removeDirRecursive(entry);
  536.     }
  537.     else {
  538.       entry.permissions = PERMS_FILE;
  539.       entry.remove(false);
  540.     }
  541.   }
  542.   dir.permissions = PERMS_DIRECTORY;
  543.   dir.remove(true);
  544. }
  545.  
  546. /**
  547.  * Logs a string to the error console.
  548.  * @param   string
  549.  *          The string to write to the error console.
  550.  */
  551. function LOG(string) {
  552.   if (gLoggingEnabled) {
  553.     dump("*** " + string + "\n");
  554.     if (gConsole)
  555.       gConsole.logStringMessage(string);
  556.   }
  557. }
  558.  
  559. /**
  560.  * Logs a string to the error console and to a permanent log file. 
  561.  * @param   string
  562.  *          The string to write out.
  563.  */  
  564. function ERROR(string) {
  565.   LOG(string);
  566.   try {
  567.     var tstamp = new Date();
  568.     var logfile = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS_LOG]);
  569.     var stream = Cc["@mozilla.org/network/file-output-stream;1"].
  570.                  createInstance(Ci.nsIFileOutputStream);
  571.     stream.init(logfile, 0x02 | 0x08 | 0x10, 0666, 0); // write, create, append
  572.     var writer = Cc["@mozilla.org/intl/converter-output-stream;1"].
  573.                  createInstance(Ci.nsIConverterOutputStream);
  574.     writer.init(stream, "UTF-8", 0, 0x0000);
  575.     string = tstamp.toLocaleFormat("%Y-%m-%d %H:%M:%S - ") + string;
  576.     writer.writeString(string + "\n");
  577.     writer.close();
  578.   }
  579.   catch (e) { }
  580. }
  581.  
  582. /**
  583.  * Randomize the specified file name. Used to force RDF to bypass the cache
  584.  * when loading certain types of files.
  585.  * @param   fileName
  586.  *          A file name to randomize, e.g. install.rdf
  587.  * @returns A randomized file name, e.g. install-xyz.rdf
  588.  */
  589. function getRandomFileName(fileName) {
  590.   var extensionDelimiter = fileName.lastIndexOf(".");
  591.   var prefix = fileName.substr(0, extensionDelimiter);
  592.   var suffix = fileName.substr(extensionDelimiter);
  593.  
  594.   var characters = "abcdefghijklmnopqrstuvwxyz0123456789";
  595.   var nameString = prefix + "-";
  596.   for (var i = 0; i < 3; ++i) {
  597.     var index = Math.round((Math.random()) * characters.length);
  598.     nameString += characters.charAt(index);
  599.   }
  600.   return nameString + "." + suffix;
  601. }
  602.  
  603. /**
  604.  * Get the RDF URI prefix of a nsIUpdateItem type. This function should be used
  605.  * ONLY to support Firefox 1.0 Update RDF files! Item URIs in the datasource
  606.  * are NOT prefixed.
  607.  * @param   type
  608.  *          The nsIUpdateItem type to find a RDF URI prefix for
  609.  * @returns The RDF URI prefix.
  610.  */
  611. function getItemPrefix(type) {
  612.   if (type & Ci.nsIUpdateItem.TYPE_EXTENSION)
  613.     return PREFIX_EXTENSION;
  614.   else if (type & Ci.nsIUpdateItem.TYPE_THEME)
  615.     return PREFIX_THEME;
  616.   return PREFIX_ITEM_URI;
  617. }
  618.  
  619. /**
  620.  * Trims a prefix from a string.
  621.  * @param   string
  622.  *          The source string
  623.  * @param   prefix
  624.  *          The prefix to remove.
  625.  * @returns The suffix (string - prefix)
  626.  */
  627. function stripPrefix(string, prefix) {
  628.   return string.substr(prefix.length);
  629. }
  630.  
  631. /**
  632.  * Gets a File URL spec for a nsIFile
  633.  * @param   file
  634.  *          The file to get a file URL spec to
  635.  * @returns The file URL spec to the file
  636.  */
  637. function getURLSpecFromFile(file) {
  638.   var ioServ = Cc["@mozilla.org/network/io-service;1"].
  639.                getService(Ci.nsIIOService);
  640.   var fph = ioServ.getProtocolHandler("file")
  641.                   .QueryInterface(Ci.nsIFileProtocolHandler);
  642.   return fph.getURLSpecFromFile(file);
  643. }
  644.  
  645. /**
  646.  * Constructs a URI to a spec.
  647.  * @param   spec
  648.  *          The spec to construct a URI to
  649.  * @returns The nsIURI constructed.
  650.  */
  651. function newURI(spec) {
  652.   var ioServ = Cc["@mozilla.org/network/io-service;1"].
  653.                getService(Ci.nsIIOService);
  654.   return ioServ.newURI(spec, null, null);
  655. }
  656.  
  657. /**
  658.  * Constructs a File URI to a nsIFile
  659.  * @param   file
  660.  *          The file to construct a File URI to
  661.  * @returns The file URI to the file
  662.  */
  663. function getURIFromFile(file) {
  664.   var ioServ = Cc["@mozilla.org/network/io-service;1"].
  665.                getService(Ci.nsIIOService);
  666.   return ioServ.newFileURI(file);
  667. }
  668.  
  669. /**
  670.  * @returns Whether or not we are currently running in safe mode.
  671.  */
  672. function inSafeMode() {
  673.   return gApp.inSafeMode;
  674. }
  675.  
  676. /**
  677.  * Extract the string value from a RDF Literal or Resource
  678.  * @param   literalOrResource
  679.  *          RDF String Literal or Resource
  680.  * @returns String value of the literal or resource, or undefined if the object
  681.  *          supplied is not a RDF string literal or resource.
  682.  */
  683. function stringData(literalOrResource) {
  684.   if (literalOrResource instanceof Ci.nsIRDFLiteral)
  685.     return literalOrResource.Value;
  686.   if (literalOrResource instanceof Ci.nsIRDFResource)
  687.     return literalOrResource.Value;
  688.   return undefined;
  689. }
  690.  
  691. /**
  692.  * Extract the integer value of a RDF Literal
  693.  * @param   literal
  694.  *          nsIRDFInt literal
  695.  * @return  integer value of the literal
  696.  */
  697. function intData(literal) {
  698.   if (literal instanceof Ci.nsIRDFInt)
  699.     return literal.Value;
  700.   return undefined;
  701. }
  702.  
  703. /**
  704.  * Gets a property from an install manifest.
  705.  * @param   installManifest
  706.  *          An Install Manifest datasource to read from
  707.  * @param   property
  708.  *          The name of a proprety to read (sans EM_NS)
  709.  * @returns The literal value of the property, or undefined if the property has
  710.  *          no value.
  711.  */
  712. function getManifestProperty(installManifest, property) {
  713.   var target = installManifest.GetTarget(gInstallManifestRoot,
  714.                                          gRDF.GetResource(EM_NS(property)), true);
  715.   var val = stringData(target);
  716.   return val === undefined ? intData(target) : val;
  717. }
  718.  
  719. /**
  720.  * Given an Install Manifest Datasource, retrieves the type of item the manifest
  721.  * describes.
  722.  * @param   installManifest
  723.  *          The Install Manifest Datasource.
  724.  * @return  The nsIUpdateItem type of the item described by the manifest
  725.  *          returns TYPE_EXTENSION if attempts to determine the type fail.
  726.  */
  727. function getAddonTypeFromInstallManifest(installManifest) {
  728.   var target = installManifest.GetTarget(gInstallManifestRoot,
  729.                                          gRDF.GetResource(EM_NS("type")), true);
  730.   if (target) {
  731.     var type = stringData(target);
  732.     return type === undefined ? intData(target) : parseInt(type);
  733.   }
  734.  
  735.   // Firefox 1.0 and earlier did not support addon-type annotation on the
  736.   // Install Manifest, so we fall back to a theme-only property to
  737.   // differentiate.
  738.   if (getManifestProperty(installManifest, "internalName") !== undefined)
  739.     return Ci.nsIUpdateItem.TYPE_THEME;
  740.  
  741.   // If no type is provided, default to "Extension"
  742.   return Ci.nsIUpdateItem.TYPE_EXTENSION;
  743. }
  744.  
  745. /**
  746.  * Shows a message about an incompatible Extension/Theme.
  747.  * @param   installData
  748.  *          An Install Data object from |getInstallData|
  749.  */
  750. function showIncompatibleError(installData) {
  751.   var extensionStrings = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  752.   var params = [extensionStrings.GetStringFromName("type-" + installData.type)];
  753.   var title = extensionStrings.formatStringFromName("incompatibleTitle",
  754.                                                     params, params.length);
  755.   params = [installData.name, installData.version, BundleManager.appName,
  756.             gApp.version];
  757.   var message = extensionStrings.formatStringFromName("incompatibleMessage",
  758.                                                       params, params.length);
  759.   var ps = Cc["@mozilla.org/embedcomp/prompt-service;1"].
  760.            getService(Ci.nsIPromptService);
  761.   ps.alert(null, title, message);
  762. }
  763.  
  764. /**
  765.  * Shows a message.
  766.  * @param   titleKey
  767.  *          String key of the title string in the Extensions localization file.
  768.  * @param   messageKey
  769.  *          String key of the message string in the Extensions localization file.
  770.  * @param   messageParams
  771.  *          Array of strings to be substituted into |messageKey|. Can be null.
  772.  */
  773. function showMessage(titleKey, titleParams, messageKey, messageParams) {
  774.   var extensionStrings = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  775.   if (titleParams && titleParams.length > 0) {
  776.     var title = extensionStrings.formatStringFromName(titleKey, titleParams,
  777.                                                       titleParams.length);
  778.   }
  779.   else
  780.     title = extensionStrings.GetStringFromName(titleKey);
  781.  
  782.   if (messageParams && messageParams.length > 0) {
  783.     var message = extensionStrings.formatStringFromName(messageKey, messageParams,
  784.                                                         messageParams.length);
  785.   }
  786.   else
  787.     message = extensionStrings.GetStringFromName(messageKey);
  788.   var ps = Cc["@mozilla.org/embedcomp/prompt-service;1"].
  789.            getService(Ci.nsIPromptService);
  790.   ps.alert(null, title, message);
  791. }
  792.  
  793. /**
  794.  * Shows a dialog for blocklisted items.
  795.  * @param   items
  796.  *          An array of nsIUpdateItems.
  797.  * @param   fromInstall
  798.  *          Whether this is called from an install or from the blocklist
  799.  *          background check.
  800.  */
  801. function showBlocklistMessage(items, fromInstall) {
  802.   var win = null;
  803.   var params = Cc["@mozilla.org/embedcomp/dialogparam;1"].
  804.                createInstance(Ci.nsIDialogParamBlock);
  805.   params.SetInt(0, (fromInstall ? 1 : 0));
  806.   params.SetInt(1, items.length);
  807.   params.SetNumberStrings(items.length * 2);
  808.   for (var i = 0; i < items.length; ++i)
  809.     params.SetString(i, items[i].name + " " + items[i].version);
  810.  
  811.   // if this was initiated from an install try to find the appropriate manager
  812.   if (fromInstall) {
  813.     var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
  814.              getService(Ci.nsIWindowMediator);
  815.     win = wm.getMostRecentWindow("Extension:Manager");
  816.   }
  817.   var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
  818.            getService(Ci.nsIWindowWatcher);
  819.   ww.openWindow(win, URI_EXTENSION_LIST_DIALOG, "",
  820.                 "chrome,centerscreen,modal,dialog,titlebar", params);
  821. }
  822.  
  823. /**
  824.  * Gets a zip reader for the file specified.
  825.  * @param   zipFile
  826.  *          A ZIP archive to open with a nsIZipReader.
  827.  * @return  A nsIZipReader for the file specified.
  828.  */
  829. function getZipReaderForFile(zipFile) {
  830.   try {
  831.     var zipReader = Cc["@mozilla.org/libjar/zip-reader;1"].
  832.                     createInstance(Ci.nsIZipReader);
  833.     zipReader.open(zipFile);
  834.   }
  835.   catch (e) {
  836.     zipReader.close();
  837.     throw e;
  838.   }
  839.   return zipReader;
  840. }
  841.  
  842. /**
  843.  * Extract a RDF file from a ZIP archive to a random location in the system
  844.  * temp directory.
  845.  * @param   zipFile
  846.  *          A ZIP archive to read from
  847.  * @param   fileName
  848.  *          The name of the file to read from the zip.
  849.  * @param   suppressErrors
  850.  *          Whether or not to report errors.
  851.  * @return  The file created in the temp directory.
  852.  */
  853. function extractRDFFileToTempDir(zipFile, fileName, suppressErrors) {
  854.   var file = getFile(KEY_TEMPDIR, [getRandomFileName(fileName)]);
  855.   try {
  856.     var zipReader = getZipReaderForFile(zipFile);
  857.     zipReader.extract(fileName, file);
  858.     zipReader.close();
  859.   }
  860.   catch (e) {
  861.     if (!suppressErrors) {
  862.       showMessage("missingFileTitle", [], "missingFileMessage",
  863.                   [BundleManager.appName, fileName]);
  864.       throw e;
  865.     }
  866.   }
  867.   return file;
  868. }
  869.  
  870. /**
  871.  * Gets an Install Manifest datasource from a file.
  872.  * @param   file
  873.  *          The nsIFile that contains the Install Manifest RDF
  874.  * @returns The Install Manifest datasource
  875.  */
  876. function getInstallManifest(file) {
  877.   var uri = getURIFromFile(file);
  878.   try {
  879.     var fis = Cc["@mozilla.org/network/file-input-stream;1"].
  880.               createInstance(Ci.nsIFileInputStream);
  881.     fis.init(file, -1, -1, false);
  882.     var bis = Cc["@mozilla.org/network/buffered-input-stream;1"].
  883.               createInstance(Ci.nsIBufferedInputStream);
  884.     bis.init(fis, 4096);
  885.     
  886.     var rdfParser = Cc["@mozilla.org/rdf/xml-parser;1"].
  887.                     createInstance(Ci.nsIRDFXMLParser)
  888.     var ds = Cc["@mozilla.org/rdf/datasource;1?name=in-memory-datasource"].
  889.              createInstance(Ci.nsIRDFDataSource);
  890.     var listener = rdfParser.parseAsync(ds, uri);
  891.     var channel = Cc["@mozilla.org/network/input-stream-channel;1"].
  892.                   createInstance(Ci.nsIInputStreamChannel);
  893.     channel.setURI(uri);
  894.     channel.contentStream = bis;
  895.     channel.QueryInterface(Ci.nsIChannel);
  896.     channel.contentType = "text/xml";
  897.   
  898.     listener.onStartRequest(channel, null);
  899.     try {
  900.       var pos = 0;
  901.       var count = bis.available();
  902.       while (count > 0) {
  903.         listener.onDataAvailable(channel, null, bis, pos, count);
  904.         pos += count;
  905.         count = bis.available();
  906.       }
  907.       listener.onStopRequest(channel, null, Components.results.NS_OK);
  908.       bis.close();
  909.       fis.close();
  910.  
  911.       var arcs = ds.ArcLabelsOut(gInstallManifestRoot);
  912.       if (arcs.hasMoreElements())
  913.         return ds;
  914.     }
  915.     catch (e) {
  916.       listener.onStopRequest(channel, null, e.result);
  917.       bis.close();
  918.       fis.close();
  919.     }
  920.   }
  921.   catch (e) { }
  922.  
  923.   var url = uri.QueryInterface(Ci.nsIURL);
  924.   showMessage("malformedTitle", [], "malformedMessage",
  925.               [BundleManager.appName, url.fileName]);
  926.   return null;
  927. }
  928.  
  929. /**
  930.  * Selects the closest matching localized resource in the given RDF resource
  931.  * @param   aDataSource The datasource to look in
  932.  * @param   aResource   The root resource containing the localized sections
  933.  * @returns The nsIRDFResource of the best em:localized section or null
  934.  *          if no valid match was found
  935.  */
  936. function findClosestLocalizedResource(aDataSource, aResource) {
  937.   var localizedProp = EM_R("localized");
  938.   var localeProp = EM_R("locale");
  939.  
  940.   // Holds the best matching localized resource
  941.   var bestmatch = null;
  942.   // The number of locale parts it matched with
  943.   var bestmatchcount = 0;
  944.   // The number of locale parts in the match
  945.   var bestpartcount = 0;
  946.  
  947.   var locales = [gLocale.toLowerCase()];
  948.   /* If the current locale is English then it will find a match if there is
  949.      a valid match for en-US so no point searching that locale too. */
  950.   if (locales[0].substring(0, 3) != "en-")
  951.     locales.push("en-us");
  952.  
  953.   for each (var locale in locales) {
  954.     var lparts = locale.split("-");
  955.     var localizations = aDataSource.GetTargets(aResource, localizedProp, true);
  956.     while (localizations.hasMoreElements()) {
  957.       var localized = localizations.getNext().QueryInterface(Ci.nsIRDFNode);
  958.       var list = aDataSource.GetTargets(localized, localeProp, true);
  959.       while (list.hasMoreElements()) {
  960.         var found = stringData(list.getNext().QueryInterface(Ci.nsIRDFNode));
  961.         if (!found)
  962.           continue;
  963.  
  964.         found = found.toLowerCase();
  965.  
  966.         // Exact match is returned immediately
  967.         if (locale == found)
  968.           return localized;
  969.   
  970.         var fparts = found.split("-");
  971.         /* If we have found a possible match and this one isn't any longer
  972.            then we dont need to check further. */
  973.         if (bestmatch && fparts.length < bestmatchcount)
  974.           continue;
  975.   
  976.         // Count the number of parts that match
  977.         var maxmatchcount = Math.min(fparts.length, lparts.length);
  978.         var matchcount = 0;
  979.         while (matchcount < maxmatchcount &&
  980.                fparts[matchcount] == lparts[matchcount])
  981.           matchcount++;
  982.   
  983.         /* If we matched more than the last best match or matched the same and
  984.            this locale is less specific than the last best match. */
  985.         if (matchcount > bestmatchcount ||
  986.            (matchcount == bestmatchcount && fparts.length < bestpartcount)) {
  987.           bestmatch = localized;
  988.           bestmatchcount = matchcount;
  989.           bestpartcount = fparts.length;
  990.         }
  991.       }
  992.     }
  993.     // If we found a valid match for this locale return it
  994.     if (bestmatch)
  995.       return bestmatch;
  996.   }
  997.   return null;
  998. }
  999.     
  1000. /**
  1001.  * An enumeration of items in a JS array.
  1002.  * @constructor
  1003.  */
  1004. function ArrayEnumerator(aItems) {
  1005.   if (aItems) {
  1006.     for (var i = 0; i < aItems.length; ++i) {
  1007.       if (!aItems[i])
  1008.         aItems.splice(i--, 1);
  1009.     }
  1010.     this._contents = aItems;
  1011.   } else {
  1012.     this._contents = [];
  1013.   }
  1014. }
  1015.  
  1016. ArrayEnumerator.prototype = {
  1017.   _index: 0,
  1018.  
  1019.   hasMoreElements: function () {
  1020.     return this._index < this._contents.length;
  1021.   },
  1022.  
  1023.   getNext: function () {
  1024.     return this._contents[this._index++];
  1025.   }
  1026. };
  1027.  
  1028. /**
  1029.  * An enumeration of files in a JS array.
  1030.  * @param   files
  1031.  *          The files to enumerate
  1032.  * @constructor
  1033.  */
  1034. function FileEnumerator(files) {
  1035.   if (files) {
  1036.     for (var i = 0; i < files.length; ++i) {
  1037.       if (!files[i])
  1038.         files.splice(i--, 1);
  1039.     }
  1040.     this._contents = files;
  1041.   } else {
  1042.     this._contents = [];
  1043.   }
  1044. }
  1045.  
  1046. FileEnumerator.prototype = {
  1047.   _index: 0,
  1048.  
  1049.   /**
  1050.    * Gets the next file in the sequence.
  1051.    */
  1052.   get nextFile() {
  1053.     if (this._index < this._contents.length)
  1054.       return this._contents[this._index++];
  1055.     return null;
  1056.   },
  1057.  
  1058.   /**
  1059.    * Stop enumerating. Nothing to do here.
  1060.    */
  1061.   close: function() {
  1062.   }
  1063. };
  1064.  
  1065. /**
  1066.  * An object which identifies an Install Location for items, where the location
  1067.  * relationship is each item living in a directory named with its GUID under
  1068.  * the directory used when constructing this object.
  1069.  *
  1070.  * e.g. <location>\{GUID1}
  1071.  *      <location>\{GUID2}
  1072.  *      <location>\{GUID3}
  1073.  *      ...
  1074.  *
  1075.  * @param   name
  1076.  *          The string identifier of this Install Location.
  1077.  * @param   location
  1078.  *          The directory that contains the items.
  1079.  * @constructor
  1080.  */
  1081. function DirectoryInstallLocation(name, location, restricted, priority, independent) {
  1082.   this._name = name;
  1083.   if (location.exists()) {
  1084.     if (!location.isDirectory())
  1085.       throw new Error("location must be a directoy!");
  1086.   }
  1087.   else {
  1088.     try {
  1089.       location.create(Ci.nsILocalFile.DIRECTORY_TYPE, 0775);
  1090.     }
  1091.     catch (e) {
  1092.       ERROR("DirectoryInstallLocation: failed to create location " +
  1093.             " directory = " + location.path + ", exception = " + e + "\n");
  1094.     }
  1095.   }
  1096.  
  1097.   this._location = location;
  1098.   this._locationToIDMap = {};
  1099.   this._restricted = restricted;
  1100.   this._priority = priority;
  1101.   this._independent = independent;
  1102. }
  1103. DirectoryInstallLocation.prototype = {
  1104.   _name           : "",
  1105.   _location       : null,
  1106.   _locationToIDMap: null,
  1107.   _restricted     : false,
  1108.   _priority       : 0,
  1109.   _independent    : false,
  1110.   _canAccess      : null,
  1111.  
  1112.   /**
  1113.    * See nsIExtensionManager.idl
  1114.    */
  1115.   get name() {
  1116.     return this._name;
  1117.   },
  1118.  
  1119.   /**
  1120.    * Reads a directory linked to in a file.
  1121.    * @param   file
  1122.    *          The file containing the directory path
  1123.    * @returns A nsILocalFile object representing the linked directory.
  1124.    */
  1125.   _readDirectoryFromFile: function(file) {
  1126.     var fis = Cc["@mozilla.org/network/file-input-stream;1"].
  1127.               createInstance(Ci.nsIFileInputStream);
  1128.     fis.init(file, -1, -1, false);
  1129.     var line = { value: "" };
  1130.     if (fis instanceof Ci.nsILineInputStream)
  1131.       fis.readLine(line);
  1132.     fis.close();
  1133.     if (line.value) {
  1134.       var linkedDirectory = Cc["@mozilla.org/file/local;1"].
  1135.                             createInstance(Ci.nsILocalFile);
  1136.       try {
  1137.         linkedDirectory.initWithPath(line.value);
  1138.       }
  1139.       catch (e) {
  1140.         linkedDirectory.setRelativeDescriptor(file.parent, line.value);
  1141.       }
  1142.  
  1143.       return linkedDirectory;
  1144.     }
  1145.     return null;
  1146.   },
  1147.  
  1148.   /**
  1149.    * See nsIExtensionManager.idl
  1150.    */
  1151.   get itemLocations() {
  1152.     var locations = [];
  1153.     if (!this._location.exists())
  1154.       return new FileEnumerator(locations);
  1155.  
  1156.     try {
  1157.       var entries = this._location.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
  1158.       while (true) {
  1159.         var entry = entries.nextFile;
  1160.         if (!entry)
  1161.           break;
  1162.         entry instanceof Ci.nsILocalFile;
  1163.         if (!entry.isDirectory() && gIDTest.test(entry.leafName)) {
  1164.           var linkedDirectory = this._readDirectoryFromFile(entry);
  1165.           if (linkedDirectory && linkedDirectory.exists() &&
  1166.               linkedDirectory.isDirectory()) {
  1167.             locations.push(linkedDirectory);
  1168.             this._locationToIDMap[linkedDirectory.persistentDescriptor] = entry.leafName;
  1169.           }
  1170.         }
  1171.         else
  1172.           locations.push(entry);
  1173.       }
  1174.       entries.close();
  1175.     }
  1176.     catch (e) {
  1177.     }
  1178.     return new FileEnumerator(locations);
  1179.   },
  1180.  
  1181.   /**
  1182.    * Retrieves the GUID for an item at the specified location.
  1183.    * @param   file
  1184.    *          The location where an item might live.
  1185.    * @returns The ID for an item that might live at the location specified.
  1186.    *
  1187.    * N.B. This function makes no promises about whether or not this path is
  1188.    *      actually maintained by this Install Location.
  1189.    */
  1190.   getIDForLocation: function(file) {
  1191.     var section = file.leafName;
  1192.     var filePD = file.persistentDescriptor;
  1193.     if (filePD in this._locationToIDMap)
  1194.       section = this._locationToIDMap[filePD];
  1195.  
  1196.     if (gIDTest.test(section))
  1197.       return RegExp.$1;
  1198.     return undefined;
  1199.   },
  1200.  
  1201.   /**
  1202.    * See nsIExtensionManager.idl
  1203.    */
  1204.   get location() {
  1205.     return this._location.clone();
  1206.   },
  1207.  
  1208.   /**
  1209.    * See nsIExtensionManager.idl
  1210.    */
  1211.   get restricted() {
  1212.     return this._restricted;
  1213.   },
  1214.  
  1215.   /**
  1216.    * See nsIExtensionManager.idl
  1217.    */
  1218.   get canAccess() {
  1219.     if (this._canAccess != null)
  1220.       return this._canAccess;
  1221.  
  1222.     var testFile = this.location;
  1223.     testFile.append("Access Privileges Test");
  1224.     try {
  1225.       testFile.createUnique(Ci.nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  1226.       testFile.remove(false);
  1227.       this._canAccess = true;
  1228.     }
  1229.     catch (e) {
  1230.       this._canAccess = false;
  1231.     }
  1232.     return this._canAccess;
  1233.   },
  1234.  
  1235.   /**
  1236.    * See nsIExtensionManager.idl
  1237.    */
  1238.   get priority() {
  1239.     return this._priority;
  1240.   },
  1241.  
  1242.   /**
  1243.    * See nsIExtensionManager.idl
  1244.    */
  1245.   getItemLocation: function(id) {
  1246.     var itemLocation = this.location;
  1247.     itemLocation.append(id);
  1248.     if (itemLocation.exists() && !itemLocation.isDirectory())
  1249.       return this._readDirectoryFromFile(itemLocation);
  1250.     if (!itemLocation.exists() && this.canAccess)
  1251.       itemLocation.create(Ci.nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  1252.     return itemLocation;
  1253.   },
  1254.  
  1255.   /**
  1256.    * See nsIExtensionManager.idl
  1257.    */
  1258.   itemIsManagedIndependently: function(id) {
  1259.     if (this._independent)
  1260.       return true;
  1261.     var itemLocation = this.location;
  1262.     itemLocation.append(id);
  1263.     return itemLocation.exists() && !itemLocation.isDirectory();
  1264.   },
  1265.  
  1266.   /**
  1267.    * See nsIExtensionManager.idl
  1268.    */
  1269.   getItemFile: function(id, filePath) {
  1270.     var itemLocation = this.getItemLocation(id).clone();
  1271.     var parts = filePath.split("/");
  1272.     for (var i = 0; i < parts.length; ++i)
  1273.       itemLocation.append(parts[i]);
  1274.     return itemLocation;
  1275.   },
  1276.  
  1277.   /**
  1278.    * Stages the specified file for later.
  1279.    * @param   file
  1280.    *          The file to stage
  1281.    * @param   id
  1282.    *          The GUID of the item the file represents
  1283.    */
  1284.   stageFile: function(file, id) {
  1285.     var stagedFile = this.location;
  1286.     stagedFile.append(DIR_STAGE);
  1287.     stagedFile.append(id);
  1288.     stagedFile.append(file.leafName);
  1289.  
  1290.     // When an incompatible update is successful the file is already staged
  1291.     if (stagedFile.equals(file))
  1292.       return stagedFile;
  1293.  
  1294.     if (stagedFile.exists())
  1295.       stagedFile.remove(false);
  1296.  
  1297.     file.copyTo(stagedFile.parent, stagedFile.leafName);
  1298.  
  1299.     // If the file has incorrect permissions set, correct them now.
  1300.     if (!stagedFile.isWritable())
  1301.       stagedFile.permissions = PERMS_FILE;
  1302.  
  1303.     return stagedFile;
  1304.   },
  1305.  
  1306.   /**
  1307.    * Returns the most recently staged package (e.g. the last XPI or JAR in a
  1308.    * directory) for an item and removes items that do not qualify.
  1309.    * @param   id
  1310.    *          The ID of the staged package
  1311.    * @returns an nsIFile if the package exists otherwise null.
  1312.    */
  1313.   getStageFile: function(id) {
  1314.     var stageFile = null;
  1315.     var stageDir = this.location;
  1316.     stageDir.append(DIR_STAGE);
  1317.     stageDir.append(id);
  1318.     if (!stageDir.exists() || !stageDir.isDirectory())
  1319.       return null;
  1320.     try {
  1321.       var entries = stageDir.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
  1322.       while (entries.hasMoreElements()) {
  1323.         var file = entries.nextFile;
  1324.         if (!(file instanceof Ci.nsILocalFile))
  1325.           continue;
  1326.         if (file.isDirectory())
  1327.           removeDirRecursive(file);
  1328.         else if (fileIsItemPackage(file)) {
  1329.           if (stageFile)
  1330.             stageFile.remove(false);
  1331.           stageFile = file;
  1332.         }
  1333.         else
  1334.           file.remove(false);
  1335.       }
  1336.     }
  1337.     catch (e) {
  1338.     }
  1339.     if (entries instanceof Ci.nsIDirectoryEnumerator)
  1340.       entries.close();
  1341.     return stageFile;
  1342.   },
  1343.  
  1344.   /**
  1345.    * Removes a file from the stage. This cleans up the stage if there is nothing
  1346.    * else left after the remove operation.
  1347.    * @param   file
  1348.    *          The file to remove.
  1349.    */
  1350.   removeFile: function(file) {
  1351.     if (file.exists())
  1352.       file.remove(false);
  1353.     var parent = file.parent;
  1354.     var entries = parent.directoryEntries;
  1355.     try {
  1356.       // XXXrstrong calling hasMoreElements on a nsIDirectoryEnumerator after
  1357.       // it has been removed will cause a crash on Mac OS X - bug 292823
  1358.       while (parent && !parent.equals(this.location) &&
  1359.             !entries.hasMoreElements()) {
  1360.         parent.remove(false);
  1361.         parent = parent.parent;
  1362.         entries = parent.directoryEntries;
  1363.       }
  1364.       if (entries instanceof Ci.nsIDirectoryEnumerator)
  1365.         entries.close();
  1366.     }
  1367.     catch (e) {
  1368.       ERROR("DirectoryInstallLocation::removeFile: failed to remove staged " +
  1369.             " directory = " + parent.path + ", exception = " + e + "\n");
  1370.     }
  1371.   },
  1372.  
  1373.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIInstallLocation])
  1374. };
  1375.  
  1376. //@line 1351 "e:\builds\tinderbox\XR-Trunk\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  1377.  
  1378. const nsIWindowsRegKey = Ci.nsIWindowsRegKey;
  1379.  
  1380. /**
  1381.  * An object that identifies the location of installed items based on entries
  1382.  * in the Windows registry.  For each application a subkey is defined that
  1383.  * contains a set of values, where the name of each value is a GUID and the
  1384.  * contents of the value is a filesystem path identifying a directory
  1385.  * containing an installed item.
  1386.  *
  1387.  * @param   name
  1388.  *          The string identifier of this Install Location.
  1389.  * @param   rootKey
  1390.  *          The root key (one of the ROOT_KEY_ values from nsIWindowsRegKey).
  1391.  * @param   restricted
  1392.  *          Indicates that the location may be restricted (e.g., this is
  1393.  *          usually true of a system level install location).
  1394.  * @param   priority
  1395.  *          The priority of this install location.
  1396.  * @constructor
  1397.  */
  1398. function WinRegInstallLocation(name, rootKey, restricted, priority) {
  1399.   this._name = name;
  1400.   this._rootKey = rootKey;
  1401.   this._restricted = restricted;
  1402.   this._priority = priority;
  1403.   this._IDToDirMap = {};
  1404.   this._DirToIDMap = {};
  1405.  
  1406.   // Reading the registry may throw an exception, and that's ok.  In error
  1407.   // cases, we just leave ourselves in the empty state.
  1408.   try {
  1409.     var path = this._appKeyPath + "\\Extensions";
  1410.     var key = Cc["@mozilla.org/windows-registry-key;1"].
  1411.               createInstance(nsIWindowsRegKey);
  1412.     key.open(this._rootKey, path, nsIWindowsRegKey.ACCESS_READ);
  1413.     this._readAddons(key);
  1414.   } catch (e) {
  1415.     if (key)
  1416.       key.close();
  1417.   }
  1418. }
  1419. WinRegInstallLocation.prototype = {
  1420.   _name       : "",
  1421.   _rootKey    : null,
  1422.   _restricted : false,
  1423.   _priority   : 0,
  1424.   _IDToDirMap : null,  // mapping from ID to directory object
  1425.   _DirToIDMap : null,  // mapping from directory path to ID
  1426.  
  1427.   /**
  1428.    * Retrieves the path of this Application's data key in the registry.
  1429.    */
  1430.   get _appKeyPath() {
  1431.     var appVendor = gApp.vendor;
  1432.     var appName = gApp.name;
  1433.  
  1434. //@line 1413 "e:\builds\tinderbox\XR-Trunk\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  1435.  
  1436.     // XULRunner-based apps may intentionally not specify a vendor:
  1437.     if (appVendor != "")
  1438.       appVendor += "\\";
  1439.  
  1440.     return "SOFTWARE\\" + appVendor + appName;
  1441.   },
  1442.  
  1443.   /**
  1444.    * Read the registry and build a mapping between GUID and directory for each
  1445.    * installed item.
  1446.    * @param   key
  1447.    *          The key that contains the GUID->path pairs
  1448.    */
  1449.   _readAddons: function(key) {
  1450.     var count = key.valueCount;
  1451.     for (var i = 0; i < count; ++i) {
  1452.       var id = key.getValueName(i);
  1453.  
  1454.       var dir = Cc["@mozilla.org/file/local;1"].
  1455.                 createInstance(Ci.nsILocalFile);
  1456.       dir.initWithPath(key.readStringValue(id));
  1457.  
  1458.       if (dir.exists() && dir.isDirectory()) {
  1459.         this._IDToDirMap[id] = dir;
  1460.         this._DirToIDMap[dir.path] = id;
  1461.       }
  1462.     }
  1463.   },
  1464.  
  1465.   get name() {
  1466.     return this._name;
  1467.   },
  1468.  
  1469.   get itemLocations() {
  1470.     var locations = [];
  1471.     for (var id in this._IDToDirMap) {
  1472.       locations.push(this._IDToDirMap[id]);
  1473.     }
  1474.     return new FileEnumerator(locations);
  1475.   },
  1476.  
  1477.   get location() {
  1478.     return null;
  1479.   },
  1480.  
  1481.   get restricted() {
  1482.     return this._restricted;
  1483.   },
  1484.  
  1485.   // you should never be able to write to this location
  1486.   get canAccess() {
  1487.     return false;
  1488.   },
  1489.  
  1490.   get priority() {
  1491.     return this._priority;
  1492.   },
  1493.  
  1494.   getItemLocation: function(id) {
  1495.     return this._IDToDirMap[id];
  1496.   },
  1497.  
  1498.   getIDForLocation: function(dir) {
  1499.     return this._DirToIDMap[dir.path];
  1500.   },
  1501.  
  1502.   getItemFile: function(id, filePath) {
  1503.     var itemLocation = this.getItemLocation(id).clone();
  1504.     var parts = filePath.split("/");
  1505.     for (var i = 0; i < parts.length; ++i)
  1506.       itemLocation.append(parts[i]);
  1507.     return itemLocation;
  1508.   },
  1509.  
  1510.   itemIsManagedIndependently: function(id) {
  1511.     return true;
  1512.   },
  1513.  
  1514.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIInstallLocation])
  1515. };
  1516.  
  1517. //@line 1496 "e:\builds\tinderbox\XR-Trunk\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  1518.  
  1519. /**
  1520.  * An object which handles the installation of an Extension.
  1521.  * @constructor
  1522.  */
  1523. function Installer(ds, id, installLocation, type) {
  1524.   this._ds = ds;
  1525.   this._id = id;
  1526.   this._type = type;
  1527.   this._installLocation = installLocation;
  1528. }
  1529. Installer.prototype = {
  1530.   // Item metadata
  1531.   _id: null,
  1532.   _ds: null,
  1533.   _installLocation: null,
  1534.   _metadataDS: null,
  1535.  
  1536.   /**
  1537.    * Gets the Install Manifest datasource we are installing from.
  1538.    */
  1539.   get metadataDS() {
  1540.     if (!this._metadataDS) {
  1541.       var metadataFile = this._installLocation
  1542.                              .getItemFile(this._id, FILE_INSTALL_MANIFEST);
  1543.       if (!metadataFile.exists())
  1544.         return null;
  1545.       this._metadataDS = getInstallManifest(metadataFile);
  1546.       if (!this._metadataDS) {
  1547.         LOG("Installer::install: metadata datasource for extension " +
  1548.             this._id + " at " + metadataFile.path + " could not be loaded. " +
  1549.             " Installation will not proceed.");
  1550.       }
  1551.     }
  1552.     return this._metadataDS;
  1553.   },
  1554.  
  1555.   /**
  1556.    * Installs the Extension
  1557.    * @param   file
  1558.    *          A XPI/JAR file to install from. If this is null or does not exist,
  1559.    *          the item is assumed to be an expanded directory, located at the GUID
  1560.    *          key in the supplied Install Location.
  1561.    */
  1562.   installFromFile: function(file) {
  1563.     // Move files from the staging dir into the extension's final home.
  1564.     if (file && file.exists()) {
  1565.       this._installExtensionFiles(file);
  1566.     }
  1567.  
  1568.     if (!this.metadataDS)
  1569.       return;
  1570.  
  1571.     // Upgrade old-style contents.rdf Chrome Manifests if necessary.
  1572.     if (this._type == Ci.nsIUpdateItem.TYPE_THEME)
  1573.       this.upgradeThemeChrome();
  1574.     else
  1575.       this.upgradeExtensionChrome();
  1576.  
  1577.     // Add metadata for the extension to the global extension metadata set
  1578.     this._ds.addItemMetadata(this._id, this.metadataDS, this._installLocation);
  1579.   },
  1580.  
  1581.   /**
  1582.    * Safely extract the Extension's files into the target folder.
  1583.    * @param   file
  1584.    *          The XPI/JAR file to install from.
  1585.    */
  1586.   _installExtensionFiles: function(file) {
  1587.     /**
  1588.       * Callback for |safeInstallOperation| that performs file level installation
  1589.       * steps for an Extension.
  1590.       * @param   extensionID
  1591.       *          The GUID of the Extension being installed.
  1592.       * @param   installLocation
  1593.       *          The Install Location where the Extension is being installed.
  1594.       * @param   xpiFile
  1595.       *          The source XPI file that contains the Extension.
  1596.       */
  1597.     function extractExtensionFiles(extensionID, installLocation, xpiFile) {
  1598.       // Create a logger to log install operations for uninstall. This must be
  1599.       // created in the |safeInstallOperation| callback, since it creates a file
  1600.       // in the target directory. If we do this outside of the callback, we may
  1601.       // be clobbering a file we should not be.
  1602.       var zipReader = getZipReaderForFile(xpiFile);
  1603.  
  1604.       // create directories first
  1605.       var entries = zipReader.findEntries("*/");
  1606.       while (entries.hasMore()) {
  1607.         var entryName = entries.getNext();
  1608.         var target = installLocation.getItemFile(extensionID, entryName);
  1609.         if (!target.exists()) {
  1610.           try {
  1611.             target.create(Ci.nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  1612.           }
  1613.           catch (e) {
  1614.             ERROR("extractExtensionsFiles: failed to create target directory for extraction " +
  1615.                   " file = " + target.path + ", exception = " + e + "\n");
  1616.           }
  1617.         }
  1618.       }
  1619.  
  1620.       entries = zipReader.findEntries(null);
  1621.       while (entries.hasMore()) {
  1622.         var entryName = entries.getNext();
  1623.         target = installLocation.getItemFile(extensionID, entryName);
  1624.         if (target.exists())
  1625.           continue;
  1626.  
  1627.         try {
  1628.           target.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1629.         }
  1630.         catch (e) {
  1631.           ERROR("extractExtensionsFiles: failed to create target file for extraction " +
  1632.                 " file = " + target.path + ", exception = " + e + "\n");
  1633.         }
  1634.         zipReader.extract(entryName, target);
  1635.       }
  1636.       zipReader.close();
  1637.     }
  1638.  
  1639.     /**
  1640.       * Callback for |safeInstallOperation| that performs file level installation
  1641.       * steps for a Theme.
  1642.       * @param   id
  1643.       *          The GUID of the Theme being installed.
  1644.       * @param   installLocation
  1645.       *          The Install Location where the Theme is being installed.
  1646.       * @param   jarFile
  1647.       *          The source JAR file that contains the Theme.
  1648.       */
  1649.     function extractThemeFiles(id, installLocation, jarFile) {
  1650.       var themeDirectory = installLocation.getItemLocation(id);
  1651.       var zipReader = getZipReaderForFile(jarFile);
  1652.  
  1653.       // The only critical file is the install.rdf and we would not have
  1654.       // gotten this far without one.
  1655.       var rootFiles = [FILE_INSTALL_MANIFEST, FILE_CHROME_MANIFEST,
  1656.                        "preview.png", "icon.png"];
  1657.       for (var i = 0; i < rootFiles.length; ++i) {
  1658.         try {
  1659.           var target = installLocation.getItemFile(id, rootFiles[i]);
  1660.           zipReader.extract(rootFiles[i], target);
  1661.         }
  1662.         catch (e) {
  1663.         }
  1664.       }
  1665.  
  1666.       var manifestFile = installLocation.getItemFile(id, FILE_CHROME_MANIFEST);
  1667.       // new theme structure requires a chrome.manifest file
  1668.       if (manifestFile.exists()) {
  1669.         var entries = zipReader.findEntries(DIR_CHROME + "/*");
  1670.         while (entries.hasMore()) {
  1671.           var entryName = entries.getNext();
  1672.           if (entryName.charAt(entryName.length - 1) == "/")
  1673.             continue;
  1674.           target = installLocation.getItemFile(id, entryName);
  1675.           try {
  1676.             target.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1677.           }
  1678.           catch (e) {
  1679.             ERROR("extractThemeFiles: failed to create target file for extraction " +
  1680.                   " file = " + target.path + ", exception = " + e + "\n");
  1681.           }
  1682.           zipReader.extract(entryName, target);
  1683.         }
  1684.         zipReader.close();
  1685.       }
  1686.       else { // old theme structure requires only an install.rdf
  1687.         try {
  1688.           var contentsManifestFile = installLocation.getItemFile(id, FILE_CONTENTS_MANIFEST);
  1689.           contentsManifestFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1690.           zipReader.extract(FILE_CONTENTS_MANIFEST, contentsManifestFile);
  1691.         }
  1692.         catch (e) {
  1693.           zipReader.close();
  1694.           ERROR("extractThemeFiles: failed to extract contents.rdf: " + target.path);
  1695.           throw e; // let the safe-op clean up
  1696.         }
  1697.         zipReader.close();
  1698.         var chromeDir = installLocation.getItemFile(id, DIR_CHROME);
  1699.         try {
  1700.           jarFile.copyTo(chromeDir, jarFile.leafName);
  1701.         }
  1702.         catch (e) {
  1703.           ERROR("extractThemeFiles: failed to copy theme JAR file to: " + chromeDir.path);
  1704.           throw e; // let the safe-op clean up
  1705.         }
  1706.  
  1707.         if (!installer.metadataDS && installer._type == Ci.nsIUpdateItem.TYPE_THEME) {
  1708.           var themeName = extensionStrings.GetStringFromName("incompatibleThemeName");
  1709.           if (contentsManifestFile && contentsManifestFile.exists()) {
  1710.             var contentsManifest = gRDF.GetDataSourceBlocking(getURLSpecFromFile(contentsManifestFile));
  1711.             try {
  1712.               var ctr = getContainer(contentsManifest,
  1713.                                      gRDF.GetResource("urn:mozilla:skin:root"));
  1714.               var elts = ctr.GetElements();
  1715.               var nameArc = gRDF.GetResource(CHROME_NS("displayName"));
  1716.               while (elts.hasMoreElements()) {
  1717.                 var elt = elts.getNext().QueryInterface(Ci.nsIRDFResource);
  1718.                 themeName = stringData(contentsManifest.GetTarget(elt, nameArc, true));
  1719.                 if (themeName)
  1720.                   break;
  1721.               }
  1722.             }
  1723.             catch (e) {
  1724.               themeName = extensionStrings.GetStringFromName("incompatibleThemeName");
  1725.             }
  1726.           }
  1727.           showIncompatibleError({ name: themeName, version: "",
  1728.                                   type: Ci.nsIUpdateItem.TYPE_THEME });
  1729.           LOG("Theme JAR file: " + jarFile.leafName + " contains an Old-Style " +
  1730.               "Theme that is not compatible with this version of the software.");
  1731.           throw new Error("Old Theme"); // let the safe-op clean up
  1732.         }
  1733.       }
  1734.     }
  1735.  
  1736.     var installer = this;
  1737.     var callback = extractExtensionFiles;
  1738.     if (this._type == Ci.nsIUpdateItem.TYPE_THEME)
  1739.       callback = extractThemeFiles;
  1740.     safeInstallOperation(this._id, this._installLocation,
  1741.                           { callback: callback, data: file });
  1742.   },
  1743.  
  1744.   /**
  1745.    * Upgrade contents.rdf Chrome Manifests used by this Theme to the new
  1746.    * chrome.manifest format if necessary.
  1747.    */
  1748.   upgradeThemeChrome: function() {
  1749.     // Use the Chrome Registry API to install the theme there
  1750.     var cr = Cc["@mozilla.org/chrome/chrome-registry;1"].
  1751.              getService(Ci.nsIToolkitChromeRegistry);
  1752.     var manifestFile = this._installLocation.getItemFile(this._id, FILE_CHROME_MANIFEST);
  1753.     if (manifestFile.exists() ||
  1754.         this._id == stripPrefix(RDFURI_DEFAULT_THEME, PREFIX_ITEM_URI))
  1755.       return;
  1756.  
  1757.     try {
  1758.       // creates a chrome manifest for themes
  1759.       var manifestURI = getURIFromFile(manifestFile);
  1760.       var chromeDir = this._installLocation.getItemFile(this._id, DIR_CHROME);
  1761.       // We're relying on the fact that there is only one JAR file
  1762.       // in the "chrome" directory. This is a hack, but it works.
  1763.       var entries = chromeDir.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
  1764.       var jarFile = entries.nextFile;
  1765.       if (jarFile) {
  1766.         var jarFileURI = getURIFromFile(jarFile);
  1767.         var contentsURI = newURI("jar:" + jarFileURI.spec + "!/");
  1768.         var contentsFile = this._installLocation.getItemFile(this._id, FILE_CONTENTS_MANIFEST);
  1769.         var contentsFileURI = getURIFromFile(contentsFile.parent);
  1770.  
  1771.         cr.processContentsManifest(contentsFileURI, manifestURI, contentsURI, false, true);
  1772.       }
  1773.       entries.close();
  1774.       contentsFile.remove(false);
  1775.     }
  1776.     catch (e) {
  1777.       // Failed to register chrome, for any number of reasons - non-existent
  1778.       // contents.rdf file at the location specified, malformed contents.rdf,
  1779.       // etc. Set the pending op to be OP_NEEDS_UNINSTALL so that the
  1780.       // extension is uninstalled properly during the subsequent uninstall
  1781.       // pass in |ExtensionManager::_finishOperations|
  1782.       ERROR("upgradeThemeChrome: failed for theme " + this._id + " - why " +
  1783.             "not convert to the new chrome.manifest format while you're at it? " +
  1784.             "Failure exception: " + e);
  1785.       showMessage("malformedRegistrationTitle", [], "malformedRegistrationMessage",
  1786.                   [BundleManager.appName]);
  1787.  
  1788.       var stageFile = this._installLocation.getStageFile(this._id);
  1789.       if (stageFile)
  1790.         this._installLocation.removeFile(stageFile);
  1791.  
  1792.       StartupCache.put(this._installLocation, this._id, OP_NEEDS_UNINSTALL, true);
  1793.       StartupCache.write();
  1794.     }
  1795.   },
  1796.  
  1797.   /**
  1798.    * Upgrade contents.rdf Chrome Manifests used by this Extension to the new
  1799.    * chrome.manifest format if necessary.
  1800.    */
  1801.   upgradeExtensionChrome: function() {
  1802.     // If the extension is aware of the new flat chrome manifests and has
  1803.     // included one, just use it instead of generating one from the
  1804.     // install.rdf/contents.rdf data.
  1805.     var manifestFile = this._installLocation.getItemFile(this._id, FILE_CHROME_MANIFEST);
  1806.     if (manifestFile.exists())
  1807.       return;
  1808.  
  1809.     try {
  1810.       // Enumerate the metadata datasource files collection and register chrome
  1811.       // for each file, calling _registerChrome for each.
  1812.       var chromeDir = this._installLocation.getItemFile(this._id, DIR_CHROME);
  1813.  
  1814.       if (!manifestFile.parent.exists())
  1815.         return;
  1816.  
  1817.       // Even if an extension doesn't have any chrome, we generate an empty
  1818.       // manifest file so that we don't try to upgrade from the "old-style"
  1819.       // chrome manifests at every startup.
  1820.       manifestFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1821.  
  1822.       var manifestURI = getURIFromFile(manifestFile);
  1823.       var files = this.metadataDS.GetTargets(gInstallManifestRoot, EM_R("file"), true);
  1824.       while (files.hasMoreElements()) {
  1825.         var file = files.getNext().QueryInterface(Ci.nsIRDFResource);
  1826.         var chromeFile = chromeDir.clone();
  1827.         var fileName = file.Value.substr("urn:mozilla:extension:file:".length, file.Value.length);
  1828.         chromeFile.append(fileName);
  1829.  
  1830.         var fileURLSpec = getURLSpecFromFile(chromeFile);
  1831.         if (!chromeFile.isDirectory()) {
  1832.           var zipReader = getZipReaderForFile(chromeFile);
  1833.           fileURLSpec = "jar:" + fileURLSpec + "!/";
  1834.           var contentsFile = this._installLocation.getItemFile(this._id, FILE_CONTENTS_MANIFEST);
  1835.           contentsFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1836.         }
  1837.  
  1838.         var providers = [EM_R("package"), EM_R("skin"), EM_R("locale")];
  1839.         for (var i = 0; i < providers.length; ++i) {
  1840.           var items = this.metadataDS.GetTargets(file, providers[i], true);
  1841.           while (items.hasMoreElements()) {
  1842.             var item = items.getNext().QueryInterface(Ci.nsIRDFLiteral);
  1843.             var fileURI = newURI(fileURLSpec + item.Value);
  1844.             // Extract the contents.rdf files instead of opening them inside of
  1845.             // the jar. This prevents the jar from being cached by the zip
  1846.             // reader which will keep the jar in use and prevent deletion.
  1847.             if (zipReader) {
  1848.               zipReader.extract(item.Value + FILE_CONTENTS_MANIFEST, contentsFile);
  1849.               var contentsFileURI = getURIFromFile(contentsFile.parent);
  1850.             }
  1851.             else
  1852.               contentsFileURI = fileURI;
  1853.  
  1854.             var cr = Cc["@mozilla.org/chrome/chrome-registry;1"].
  1855.                      getService(Ci.nsIToolkitChromeRegistry);
  1856.             cr.processContentsManifest(contentsFileURI, manifestURI, fileURI, true, false);
  1857.           }
  1858.         }
  1859.         if (zipReader) {
  1860.           zipReader.close();
  1861.           zipReader = null;
  1862.           contentsFile.remove(false);
  1863.         }
  1864.       }
  1865.     }
  1866.     catch (e) {
  1867.       // Failed to register chrome, for any number of reasons - non-existent
  1868.       // contents.rdf file at the location specified, malformed contents.rdf,
  1869.       // etc. Set the pending op to be OP_NEEDS_UNINSTALL so that the
  1870.       // extension is uninstalled properly during the subsequent uninstall
  1871.       // pass in |ExtensionManager::_finishOperations|
  1872.       ERROR("upgradeExtensionChrome: failed for extension " + this._id + " - why " +
  1873.             "not convert to the new chrome.manifest format while you're at it? " +
  1874.             "Failure exception: " + e);
  1875.       showMessage("malformedRegistrationTitle", [], "malformedRegistrationMessage",
  1876.                   [BundleManager.appName]);
  1877.  
  1878.       var stageFile = this._installLocation.getStageFile(this._id);
  1879.       if (stageFile)
  1880.         this._installLocation.removeFile(stageFile);
  1881.  
  1882.       StartupCache.put(this._installLocation, this._id, OP_NEEDS_UNINSTALL, true);
  1883.       StartupCache.write();
  1884.     }
  1885.   }
  1886. };
  1887.  
  1888. /**
  1889.  * Safely attempt to perform a caller-defined install operation for a given
  1890.  * item ID. Using aggressive success-safety checks, this function will attempt
  1891.  * to move an existing location for an item aside and then allow installation
  1892.  * into the appropriate folder. If any operation fails the installation will
  1893.  * abort and roll back from the moved-aside old version.
  1894.  * @param   itemID
  1895.  *          The GUID of the item to perform the operation on.
  1896.  * @param   installLocation
  1897.  *          The Install Location where the item is installed.
  1898.  * @param   installCallback
  1899.  *          A caller supplied JS object with the following properties:
  1900.  *          "data"      A data parameter to be passed to the callback.
  1901.  *          "callback"  A function to perform the install operation. This
  1902.  *                      function is passed three parameters:
  1903.  *                      1. The GUID of the item being operated on.
  1904.  *                      2. The Install Location where the item is installed.
  1905.  *                      3. The "data" parameter on the installCallback object.
  1906.  */
  1907. function safeInstallOperation(itemID, installLocation, installCallback) {
  1908.   var movedFiles = [];
  1909.  
  1910.   /**
  1911.    * Reverts a deep move by moving backed up files back to their original
  1912.    * location.
  1913.    */
  1914.   function rollbackMove()
  1915.   {
  1916.     for (var i = 0; i < movedFiles.length; ++i) {
  1917.       var oldFile = movedFiles[i].oldFile;
  1918.       var newFile = movedFiles[i].newFile;
  1919.       try {
  1920.         newFile.moveTo(oldFile.parent, newFile.leafName);
  1921.       }
  1922.       catch (e) {
  1923.         ERROR("safeInstallOperation: failed to roll back files after an install " +
  1924.               "operation failed. Failed to roll back: " + newFile.path + " to: " +
  1925.               oldFile.path + " ... aborting installation.");
  1926.         throw e;
  1927.       }
  1928.     }
  1929.   }
  1930.  
  1931.   /**
  1932.    * Moves a file to a new folder.
  1933.    * @param   file
  1934.    *          The file to move
  1935.    * @param   destination
  1936.    *          The target folder
  1937.    */
  1938.   function moveFile(file, destination) {
  1939.     try {
  1940.       var oldFile = file.clone();
  1941.       file.moveTo(destination, file.leafName);
  1942.       movedFiles.push({ oldFile: oldFile, newFile: file });
  1943.     }
  1944.     catch (e) {
  1945.       ERROR("safeInstallOperation: failed to back up file: " + file.path + " to: " +
  1946.             destination.path + " ... rolling back file moves and aborting " +
  1947.             "installation.");
  1948.       rollbackMove();
  1949.       throw e;
  1950.     }
  1951.   }
  1952.  
  1953.   /**
  1954.    * Moves a directory to a new location. If any part of the move fails,
  1955.    * files already moved will be rolled back.
  1956.    * @param   sourceDir
  1957.    *          The directory to move
  1958.    * @param   targetDir
  1959.    *          The destination directory
  1960.    * @param   currentDir
  1961.    *          The current directory (a subdirectory of |sourceDir| or
  1962.    *          |sourceDir| itself) we are moving files from.
  1963.    */
  1964.   function moveDirectory(sourceDir, targetDir, currentDir) {
  1965.     var entries = currentDir.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
  1966.     while (true) {
  1967.       var entry = entries.nextFile;
  1968.       if (!entry)
  1969.         break;
  1970.       if (entry.isDirectory())
  1971.         moveDirectory(sourceDir, targetDir, entry);
  1972.       else if (entry instanceof Ci.nsILocalFile) {
  1973.         var rd = entry.getRelativeDescriptor(sourceDir);
  1974.         var destination = targetDir.clone().QueryInterface(Ci.nsILocalFile);
  1975.         destination.setRelativeDescriptor(targetDir, rd);
  1976.         moveFile(entry, destination.parent);
  1977.       }
  1978.     }
  1979.     entries.close();
  1980.   }
  1981.  
  1982.   /**
  1983.    * Removes the temporary backup directory where we stored files.
  1984.    * @param   directory
  1985.    *          The backup directory to remove
  1986.    */
  1987.   function cleanUpTrash(directory) {
  1988.     try {
  1989.       // Us-generated. Safe.
  1990.       if (directory && directory.exists())
  1991.         removeDirRecursive(directory);
  1992.     }
  1993.     catch (e) {
  1994.       ERROR("safeInstallOperation: failed to clean up the temporary backup of the " +
  1995.             "older version: " + itemLocationTrash.path);
  1996.       // This is a non-fatal error. Annoying, but non-fatal.
  1997.     }
  1998.   }
  1999.  
  2000.   if (!installLocation.itemIsManagedIndependently(itemID)) {
  2001.     var itemLocation = installLocation.getItemLocation(itemID);
  2002.     if (itemLocation.exists()) {
  2003.       var trashDirName = itemID + "-trash";
  2004.       var itemLocationTrash = itemLocation.parent.clone();
  2005.       itemLocationTrash.append(trashDirName);
  2006.       if (itemLocationTrash.exists()) {
  2007.         // We can remove recursively here since this is a folder we created, not
  2008.         // one the user specified. If this fails, it'll throw, and the caller
  2009.         // should stop installation.
  2010.         try {
  2011.           removeDirRecursive(itemLocationTrash);
  2012.         }
  2013.         catch (e) {
  2014.           ERROR("safeFileOperation: failed to remove existing trash directory " +
  2015.                 itemLocationTrash.path + " ... aborting installation.");
  2016.           throw e;
  2017.         }
  2018.       }
  2019.  
  2020.       // Move the directory that contains the existing version of the item aside,
  2021.       // into {GUID}-trash. This will throw if there's a failure and the install
  2022.       // will abort.
  2023.       moveDirectory(itemLocation, itemLocationTrash, itemLocation);
  2024.  
  2025.       // Clean up the original location, if necessary. Again, this is a path we
  2026.       // generated, so it is safe to recursively delete.
  2027.       try {
  2028.         removeDirRecursive(itemLocation);
  2029.       }
  2030.       catch (e) {
  2031.         ERROR("safeInstallOperation: failed to clean up item location after its contents " +
  2032.               "were properly backed up. Failed to clean up: " + itemLocation.path +
  2033.               " ... rolling back file moves and aborting installation.");
  2034.         rollbackMove();
  2035.         cleanUpTrash(itemLocationTrash);
  2036.         throw e;
  2037.       }
  2038.     }
  2039.   }
  2040.   else if (installLocation.name == KEY_APP_PROFILE ||
  2041.            installLocation.name == KEY_APP_GLOBAL ||
  2042.            installLocation.name == KEY_APP_SYSTEM_USER) {
  2043.     // Check for a pointer file and move it aside if it exists
  2044.     var pointerFile = installLocation.location.clone();
  2045.     pointerFile.append(itemID);
  2046.     if (pointerFile.exists() && !pointerFile.isDirectory()) {
  2047.       var trashFileName = itemID + "-trash";
  2048.       var itemLocationTrash = installLocation.location.clone();
  2049.       itemLocationTrash.append(trashFileName);
  2050.       if (itemLocationTrash.exists()) {
  2051.         // We can remove recursively here since this is a folder we created, not
  2052.         // one the user specified. If this fails, it'll throw, and the caller
  2053.         // should stop installation.
  2054.         try {
  2055.           removeDirRecursive(itemLocationTrash);
  2056.         }
  2057.         catch (e) {
  2058.           ERROR("safeFileOperation: failed to remove existing trash directory " +
  2059.                 itemLocationTrash.path + " ... aborting installation.");
  2060.           throw e;
  2061.         }
  2062.       }
  2063.       itemLocationTrash.create(Ci.nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  2064.       // Move the pointer file to the trash.
  2065.       moveFile(pointerFile, itemLocationTrash);
  2066.     }
  2067.   }
  2068.  
  2069.   // Now tell the client to do their stuff.
  2070.   try {
  2071.     installCallback.callback(itemID, installLocation, installCallback.data);
  2072.   }
  2073.   catch (e) {
  2074.     // This means the install operation failed. Remove everything and roll back.
  2075.     ERROR("safeInstallOperation: install operation (caller-supplied callback) failed, " +
  2076.           "rolling back file moves and aborting installation.");
  2077.     try {
  2078.       // Us-generated. Safe.
  2079.       removeDirRecursive(itemLocation);
  2080.     }
  2081.     catch (e) {
  2082.       ERROR("safeInstallOperation: failed to remove the folder we failed to install " +
  2083.             "an item into: " + itemLocation.path + " -- There is not much to suggest " +
  2084.             "here... maybe restart and try again?");
  2085.       cleanUpTrash(itemLocationTrash);
  2086.       throw e;
  2087.     }
  2088.     rollbackMove();
  2089.     cleanUpTrash(itemLocationTrash);
  2090.     throw e;
  2091.   }
  2092.  
  2093.   // Now, and only now - after everything else has succeeded (against all odds!)
  2094.   // remove the {GUID}-trash directory where we stashed the old version of the
  2095.   // item.
  2096.   cleanUpTrash(itemLocationTrash);
  2097. }
  2098.  
  2099. /**
  2100.  * Manages the list of pending operations.
  2101.  */
  2102. var PendingOperations = {
  2103.   _ops: { },
  2104.  
  2105.   /**
  2106.    * Adds an entry to the Pending Operations List
  2107.    * @param   opType
  2108.    *          The type of Operation to be performed
  2109.    * @param   entry
  2110.    *          A JS Object representing the item to be operated on:
  2111.    *          "locationKey"   The name of the Install Location where the item
  2112.    *                          is installed.
  2113.    *          "id"            The GUID of the item.
  2114.    */
  2115.   addItem: function(opType, entry) {
  2116.     if (opType == OP_NONE)
  2117.       this.clearOpsForItem(entry.id);
  2118.     else {
  2119.       if (!(opType in this._ops))
  2120.         this._ops[opType] = { };
  2121.       this._ops[opType][entry.id] = entry.locationKey;
  2122.     }
  2123.   },
  2124.  
  2125.   /**
  2126.    * Removes a Pending Operation from the list
  2127.    * @param   opType
  2128.    *          The type of Operation being removed
  2129.    * @param   id
  2130.    *          The GUID of the item to remove the entry for
  2131.    */
  2132.   clearItem: function(opType, id) {
  2133.     if (opType in this._ops && id in this._ops[opType])
  2134.       delete this._ops[opType][id];
  2135.   },
  2136.  
  2137.   /**
  2138.    * Removes all Pending Operation for an item
  2139.    * @param   id
  2140.    *          The ID of the item to remove the entries for
  2141.    */
  2142.   clearOpsForItem: function(id) {
  2143.     for (var opType in this._ops) {
  2144.       if (id in this._ops[opType])
  2145.         delete this._ops[opType][id];
  2146.     }
  2147.   },
  2148.  
  2149.   /**
  2150.    * Remove all Pending Operations of a certain type
  2151.    * @param   opType
  2152.    *          The type of Operation to remove all entries for
  2153.    */
  2154.   clearItems: function(opType) {
  2155.     if (opType in this._ops)
  2156.       delete this._ops[opType];
  2157.   },
  2158.  
  2159.   /**
  2160.    * Get an array of operations of a certain type
  2161.    * @param   opType
  2162.    *          The type of Operation to return a list of
  2163.    */
  2164.   getOperations: function(opType) {
  2165.     if (!(opType in this._ops))
  2166.       return [];
  2167.     var ops = [];
  2168.     for (var id in this._ops[opType])
  2169.       ops.push( {id: id, locationKey: this._ops[opType][id] } );
  2170.     return ops;
  2171.   },
  2172.  
  2173.   /**
  2174.    * The total number of Pending Operations, for all types.
  2175.    */
  2176.   get size() {
  2177.     var size = 0;
  2178.     for (var opType in this._ops) {
  2179.       for (var id in this._ops[opType])
  2180.         ++size;
  2181.     }
  2182.     return size;
  2183.   }
  2184. };
  2185.  
  2186. /**
  2187.  * Manages registered Install Locations
  2188.  */
  2189. var InstallLocations = {
  2190.   _locations: { },
  2191.  
  2192.   /**
  2193.    * A nsISimpleEnumerator of all available Install Locations.
  2194.    */
  2195.   get enumeration() {
  2196.     var installLocations = [];
  2197.     for (var key in this._locations)
  2198.       installLocations.push(InstallLocations.get(key));
  2199.     return new ArrayEnumerator(installLocations);
  2200.   },
  2201.  
  2202.   /**
  2203.    * Gets a named Install Location
  2204.    * @param   name
  2205.    *          The name of the Install Location to get
  2206.    */
  2207.   get: function(name) {
  2208.     return name in this._locations ? this._locations[name] : null;
  2209.   },
  2210.  
  2211.   /**
  2212.    * Registers an Install Location
  2213.    * @param   installLocation
  2214.    *          The Install Location to register
  2215.    */
  2216.   put: function(installLocation) {
  2217.     this._locations[installLocation.name] = installLocation;
  2218.   }
  2219. };
  2220.  
  2221. /**
  2222.  * Manages the Startup Cache. The Startup Cache is a representation
  2223.  * of the contents of extensions.cache, a list of all
  2224.  * items the Extension System knows about, whether or not they
  2225.  * are active or visible.
  2226.  */
  2227. var StartupCache = {
  2228.   /**
  2229.    * Location Name -> GUID hash of entries from the Startup Cache file
  2230.    * Each entry has the following properties:
  2231.    *  "descriptor"    The location on disk of the item
  2232.    *  "mtime"         The time the location was last modified
  2233.    *  "op"            Any pending operations on this item.
  2234.    *  "location"      The Install Location name where the item is installed.
  2235.    */
  2236.   entries: { },
  2237.  
  2238.   /**
  2239.    * Puts an entry into the Startup Cache
  2240.    * @param   installLocation
  2241.    *          The Install Location where the item is installed
  2242.    * @param   id
  2243.    *          The GUID of the item
  2244.    * @param   op
  2245.    *          The name of the operation to be performed
  2246.    * @param   shouldCreate
  2247.    *          Whether or not we should create a new entry for this item
  2248.    *          in the cache if one does not already exist.
  2249.    */
  2250.   put: function(installLocation, id, op, shouldCreate) {
  2251.     var itemLocation = installLocation.getItemLocation(id);
  2252.  
  2253.     var descriptor = null;
  2254.     var mtime = null;
  2255.     if (itemLocation) {
  2256.       itemLocation.QueryInterface(Ci.nsILocalFile);
  2257.       descriptor = getDescriptorFromFile(itemLocation, installLocation);
  2258.       if (itemLocation.exists() && itemLocation.isDirectory())
  2259.         mtime = Math.floor(itemLocation.lastModifiedTime / 1000);
  2260.     }
  2261.  
  2262.     this._putRaw(installLocation.name, id, descriptor, mtime, op, shouldCreate);
  2263.   },
  2264.  
  2265.   /**
  2266.    * Private helper function for putting an entry into the Startup Cache
  2267.    * without relying on the presence of its associated nsIInstallLocation
  2268.    * instance.
  2269.    *
  2270.    * @param key
  2271.    *        The install location name.
  2272.    * @param id
  2273.    *        The ID of the item.
  2274.    * @param descriptor
  2275.    *        Value returned from absoluteDescriptor.  May be null, in which
  2276.    *        case the descriptor field is not updated.
  2277.    * @param mtime
  2278.    *        The last modified time of the item.  May be null, in which case the
  2279.    *        descriptor field is not updated.
  2280.    * @param op
  2281.    *        The OP code to store with the entry.
  2282.    * @param shouldCreate
  2283.    *        Boolean value indicating whether to create or delete the entry.
  2284.    */
  2285.   _putRaw: function(key, id, descriptor, mtime, op, shouldCreate) {
  2286.     if (!(key in this.entries))
  2287.       this.entries[key] = { };
  2288.     if (!(id in this.entries[key]))
  2289.       this.entries[key][id] = { };
  2290.     if (shouldCreate) {
  2291.       if (!this.entries[key][id])
  2292.         this.entries[key][id] = { };
  2293.  
  2294.       var entry = this.entries[key][id];
  2295.  
  2296.       if (descriptor)
  2297.         entry.descriptor = descriptor;
  2298.       if (mtime)
  2299.         entry.mtime = mtime;
  2300.       entry.op = op;
  2301.       entry.location = key;
  2302.     }
  2303.     else
  2304.       this.entries[key][id] = null;
  2305.   },
  2306.  
  2307.   /**
  2308.    * Clears an entry from the Startup Cache
  2309.    * @param   installLocation
  2310.    *          The Install Location where item is installed
  2311.    * @param   id
  2312.    *          The GUID of the item.
  2313.    */
  2314.   clearEntry: function(installLocation, id) {
  2315.     var key = installLocation.name;
  2316.     if (key in this.entries && id in this.entries[key])
  2317.       this.entries[key][id] = null;
  2318.   },
  2319.  
  2320.   /**
  2321.    * Get all the startup cache entries for a particular ID.
  2322.    * @param   id
  2323.    *          The GUID of the item to locate.
  2324.    * @returns An array of Startup Cache entries for the specified ID.
  2325.    */
  2326.   findEntries: function(id) {
  2327.     var entries = [];
  2328.     for (var key in this.entries) {
  2329.       if (id in this.entries[key])
  2330.         entries.push(this.entries[key][id]);
  2331.     }
  2332.     return entries;
  2333.   },
  2334.  
  2335.   /**
  2336.    * Read the Item-Change manifest file into a hash of properties.
  2337.    * The Item-Change manifest currently holds a list of paths, with the last
  2338.    * mtime for each path, and the GUID of the item at that path.
  2339.    */
  2340.   read: function() {
  2341.     var itemChangeManifest = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS_STARTUP_CACHE]);
  2342.     if (!itemChangeManifest.exists()) {
  2343.       // There is no change manifest for some reason, either we're in an initial
  2344.       // state or something went wrong with one of the other files and the
  2345.       // change manifest was removed. Return an empty dataset and rebuild.
  2346.       gFirstRun = true;
  2347.       return;
  2348.     }
  2349.     var fis = Cc["@mozilla.org/network/file-input-stream;1"].
  2350.               createInstance(Ci.nsIFileInputStream);
  2351.     fis.init(itemChangeManifest, -1, -1, false);
  2352.     if (fis instanceof Ci.nsILineInputStream) {
  2353.       var line = { value: "" };
  2354.       var more = false;
  2355.       do {
  2356.         more = fis.readLine(line);
  2357.         if (line.value) {
  2358.           // The Item-Change manifest is formatted like so:
  2359.           //  (pd = descriptor)
  2360.           // location-key\tguid-of-item\tpd-to-extension1\tmtime-of-pd\tpending-op
  2361.           // location-key\tguid-of-item\tpd-to-extension2\tmtime-of-pd\tpending-op
  2362.           // ...
  2363.           // We hash on location-key first, because we don't want to have to
  2364.           // spin up the main extensions datasource on every start to determine
  2365.           // the Install Location for an item.
  2366.           // We hash on guid second, because we want a way to quickly determine
  2367.           // item GUID during a check loop that runs on every startup.
  2368.           var parts = line.value.split("\t");
  2369.           // Silently drop any entries in unknown install locations
  2370.           if (!InstallLocations.get(parts[0]))
  2371.             continue;
  2372.           var op = parts[4];
  2373.           this._putRaw(parts[0], parts[1], parts[2], parts[3], op, true);
  2374.           if (op)
  2375.             PendingOperations.addItem(op, { locationKey: parts[0], id: parts[1] });
  2376.         }
  2377.       }
  2378.       while (more);
  2379.     }
  2380.     fis.close();
  2381.   },
  2382.  
  2383.   /**
  2384.    * Writes the Startup Cache to disk
  2385.    */
  2386.   write: function() {
  2387.     var extensionsCacheFile = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS_STARTUP_CACHE]);
  2388.     var fos = openSafeFileOutputStream(extensionsCacheFile);
  2389.     for (var locationKey in this.entries) {
  2390.       for (var id in this.entries[locationKey]) {
  2391.         var entry = this.entries[locationKey][id];
  2392.         if (entry) {
  2393.           try {
  2394.             var itemLocation = getFileFromDescriptor(entry.descriptor, InstallLocations.get(locationKey));
  2395.  
  2396.             // Update our knowledge of this item's last-modified-time.
  2397.             // XXXdarin: this may cause us to miss changes in some cases.
  2398.             var itemMTime = 0;
  2399.             if (itemLocation.exists() && itemLocation.isDirectory())
  2400.               itemMTime = Math.floor(itemLocation.lastModifiedTime / 1000);
  2401.  
  2402.             // Each line in the startup cache manifest is in this form:
  2403.             // location-key\tid-of-item\tpd-to-extension1\tmtime-of-pd\tpending-op
  2404.             var line = locationKey + "\t" + id + "\t" + entry.descriptor + "\t" +
  2405.                        itemMTime + "\t" + entry.op + "\r\n";
  2406.             fos.write(line, line.length);
  2407.           }
  2408.           catch (e) {}
  2409.         }
  2410.       }
  2411.     }
  2412.     closeSafeFileOutputStream(fos);
  2413.   }
  2414. };
  2415.  
  2416. /**
  2417.  * Installs, manages and tracks compatibility for Extensions and Themes
  2418.  * @constructor
  2419.  */
  2420. function ExtensionManager() {
  2421.   gApp = Cc["@mozilla.org/xre/app-info;1"].
  2422.          getService(Ci.nsIXULAppInfo).QueryInterface(Ci.nsIXULRuntime);
  2423.   gOSTarget = gApp.OS;
  2424.   try {
  2425.     gXPCOMABI = gApp.XPCOMABI;
  2426.   } catch (ex) {
  2427.     // Provide a default for gXPCOMABI. It won't be compared to an
  2428.     // item's metadata (i.e. install.rdf can't specify e.g. WINNT_unknownABI
  2429.     // as targetPlatform), but it will be displayed in error messages and
  2430.     // transmitted to update URLs.
  2431.     gXPCOMABI = UNKNOWN_XPCOM_ABI;
  2432.   }
  2433.   gPref = Cc["@mozilla.org/preferences-service;1"].
  2434.           getService(Ci.nsIPrefBranch2);
  2435.  
  2436.   gOS = Cc["@mozilla.org/observer-service;1"].
  2437.         getService(Ci.nsIObserverService);
  2438.   gOS.addObserver(this, "xpcom-shutdown", false);
  2439.  
  2440.   gConsole = Cc["@mozilla.org/consoleservice;1"].
  2441.              getService(Ci.nsIConsoleService);
  2442.  
  2443.   gRDF = Cc["@mozilla.org/rdf/rdf-service;1"].
  2444.          getService(Ci.nsIRDFService);
  2445.   gInstallManifestRoot = gRDF.GetResource(RDFURI_INSTALL_MANIFEST_ROOT);
  2446.  
  2447.   // Register Global Install Location
  2448.   var appGlobalExtensions = getDirNoCreate(KEY_APPDIR, [DIR_EXTENSIONS]);
  2449.   var priority = Ci.nsIInstallLocation.PRIORITY_APP_SYSTEM_GLOBAL;
  2450.   var globalLocation = new DirectoryInstallLocation(KEY_APP_GLOBAL,
  2451.                                                     appGlobalExtensions, true,
  2452.                                                     priority, false);
  2453.   InstallLocations.put(globalLocation);
  2454.  
  2455.   // Register App-Profile Install Location
  2456.   var appProfileExtensions = getDirNoCreate(KEY_PROFILEDS, [DIR_EXTENSIONS]);
  2457.   var priority = Ci.nsIInstallLocation.PRIORITY_APP_PROFILE;
  2458.   var profileLocation = new DirectoryInstallLocation(KEY_APP_PROFILE,
  2459.                                                      appProfileExtensions, false,
  2460.                                                      priority, false);
  2461.   InstallLocations.put(profileLocation);
  2462.  
  2463.   // Register per-user Install Location
  2464.   try {
  2465.     var appSystemUExtensions = getDirNoCreate("XREUSysExt", [gApp.ID]);
  2466.   }
  2467.   catch(e) { }
  2468.  
  2469.   if (appSystemUExtensions) {
  2470.     var priority = Ci.nsIInstallLocation.PRIORITY_APP_SYSTEM_USER;
  2471.     var systemLocation = new DirectoryInstallLocation(KEY_APP_SYSTEM_USER,
  2472.                                                       appSystemUExtensions, false,
  2473.                                                       priority, true);
  2474.  
  2475.     InstallLocations.put(systemLocation);
  2476.   }
  2477.  
  2478.   // Register App-System-Shared Install Location
  2479.   try {
  2480.     var appSystemSExtensions = getDirNoCreate("XRESysSExtPD", [gApp.ID]);
  2481.   }
  2482.   catch (e) { }
  2483.  
  2484.   if (appSystemSExtensions) {
  2485.     var priority = Ci.nsIInstallLocation.PRIORITY_APP_SYSTEM_GLOBAL + 10;
  2486.     var systemLocation = new DirectoryInstallLocation(KEY_APP_SYSTEM_SHARE,
  2487.                                                       appSystemSExtensions, true,
  2488.                                                       priority, true);
  2489.     InstallLocations.put(systemLocation);
  2490.   }
  2491.  
  2492.   // Register App-System-Local Install Location
  2493.   try {
  2494.     var appSystemLExtensions = getDirNoCreate("XRESysLExtPD", [gApp.ID]);
  2495.   }
  2496.   catch (e) { }
  2497.  
  2498.   if (appSystemLExtensions) {
  2499.     var priority = Ci.nsIInstallLocation.PRIORITY_APP_SYSTEM_GLOBAL + 20;
  2500.     var systemLocation = new DirectoryInstallLocation(KEY_APP_SYSTEM_LOCAL,
  2501.                                                       appSystemLExtensions, true,
  2502.                                                       priority, true);
  2503.     InstallLocations.put(systemLocation);
  2504.   }
  2505.  
  2506. //@line 2485 "e:\builds\tinderbox\XR-Trunk\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  2507.   // Register HKEY_LOCAL_MACHINE Install Location
  2508.   InstallLocations.put(
  2509.       new WinRegInstallLocation("winreg-app-global",
  2510.                                 nsIWindowsRegKey.ROOT_KEY_LOCAL_MACHINE,
  2511.                                 true,
  2512.                                 Ci.nsIInstallLocation.PRIORITY_APP_SYSTEM_GLOBAL + 10));
  2513.  
  2514.   // Register HKEY_CURRENT_USER Install Location
  2515.   InstallLocations.put(
  2516.       new WinRegInstallLocation("winreg-app-user",
  2517.                                 nsIWindowsRegKey.ROOT_KEY_CURRENT_USER,
  2518.                                 false,
  2519.                                 Ci.nsIInstallLocation.PRIORITY_APP_SYSTEM_USER + 10));
  2520. //@line 2499 "e:\builds\tinderbox\XR-Trunk\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  2521.  
  2522.   // Register Additional Install Locations
  2523.   var categoryManager = Cc["@mozilla.org/categorymanager;1"].
  2524.                         getService(Ci.nsICategoryManager);
  2525.   var locations = categoryManager.enumerateCategory(CATEGORY_INSTALL_LOCATIONS);
  2526.   while (locations.hasMoreElements()) {
  2527.     var entry = locations.getNext().QueryInterface(Ci.nsISupportsCString).data;
  2528.     var contractID = categoryManager.getCategoryEntry(CATEGORY_INSTALL_LOCATIONS, entry);
  2529.     var location = Cc[contractID].getService(Ci.nsIInstallLocation);
  2530.     InstallLocations.put(location);
  2531.   }
  2532. }
  2533.  
  2534. ExtensionManager.prototype = {
  2535.   /**
  2536.    * See nsIObserver.idl
  2537.    */
  2538.   observe: function(subject, topic, data) {
  2539.     switch (topic) {
  2540.     case "app-startup":
  2541.       gOS.addObserver(this, "profile-after-change", false);
  2542.       gOS.addObserver(this, "quit-application", false);
  2543.       break;
  2544.     case "profile-after-change":
  2545.       this._profileSelected();
  2546.       break;
  2547.     case "quit-application-requested":
  2548.       this._confirmCancelDownloadsOnQuit(subject);
  2549.       break;
  2550.     case "offline-requested":
  2551.       this._confirmCancelDownloadsOnOffline(subject);
  2552.       break;
  2553.     case "quit-application":
  2554.       gOS.removeObserver(this, "profile-after-change");
  2555.       gOS.removeObserver(this, "quit-application");
  2556.       break;
  2557.     case "xpcom-shutdown":
  2558.       this._shutdown();
  2559.       break;
  2560.     case "nsPref:changed":
  2561.       if (data == PREF_EM_LOGGING_ENABLED)
  2562.         this._loggingToggled();
  2563.       else if (data == PREF_EM_CHECK_COMPATIBILITY ||
  2564.                data == PREF_EM_CHECK_UPDATE_SECURITY)
  2565.         this._updateAppDisabledState();
  2566.       else if ((data == PREF_MATCH_OS_LOCALE) || (data == PREF_SELECTED_LOCALE))
  2567.         this._updateLocale();
  2568.       break;
  2569.     }
  2570.   },
  2571.  
  2572.   /**
  2573.    * Refresh the logging enabled global from preferences when the user changes
  2574.    * the preference settting.
  2575.    */
  2576.   _loggingToggled: function() {
  2577.     gLoggingEnabled = getPref("getBoolPref", PREF_EM_LOGGING_ENABLED, false);
  2578.   },
  2579.  
  2580.   /**
  2581.    * Retrieves the current locale
  2582.    */
  2583.   _updateLocale: function() {
  2584.     try {
  2585.       if (gPref.getBoolPref(PREF_MATCH_OS_LOCALE)) {
  2586.         var localeSvc = Cc["@mozilla.org/intl/nslocaleservice;1"].
  2587.                         getService(Ci.nsILocaleService);
  2588.         gLocale = localeSvc.getLocaleComponentForUserAgent();
  2589.         return;
  2590.       }
  2591.     }
  2592.     catch (ex) {
  2593.     }
  2594.     gLocale = gPref.getCharPref(PREF_SELECTED_LOCALE);
  2595.   },
  2596.  
  2597.   /**
  2598.    * When a preference is toggled that affects whether an item is usable or not
  2599.    * we must app-enable or app-disable the item based on the new settings.
  2600.    */
  2601.   _updateAppDisabledState: function() {
  2602.     gCheckCompatibility = getPref("getBoolPref", PREF_EM_CHECK_COMPATIBILITY, true);
  2603.     gCheckUpdateSecurity = getPref("getBoolPref", PREF_EM_CHECK_UPDATE_SECURITY, true);
  2604.     var ds = this.datasource;
  2605.  
  2606.     // Enumerate all items
  2607.     var ctr = getContainer(ds, ds._itemRoot);
  2608.     var elements = ctr.GetElements();
  2609.     while (elements.hasMoreElements()) {
  2610.       var itemResource = elements.getNext().QueryInterface(Ci.nsIRDFResource);
  2611.  
  2612.       // App disable or enable items as necessary
  2613.       // _appEnableItem and _appDisableItem will do nothing if the item is already
  2614.       // in the right state.
  2615.       id = stripPrefix(itemResource.Value, PREFIX_ITEM_URI);
  2616.       if (this._isUsableItem(id))
  2617.         this._appEnableItem(id);
  2618.       else
  2619.         this._appDisableItem(id);
  2620.     }
  2621.   },
  2622.  
  2623.   /**
  2624.    * Initialize the system after a profile has been selected.
  2625.    */
  2626.   _profileSelected: function() {
  2627.     // Tell the Chrome Registry which Skin to select
  2628.     try {
  2629.       if (gPref.getBoolPref(PREF_DSS_SWITCHPENDING)) {
  2630.         var toSelect = gPref.getCharPref(PREF_DSS_SKIN_TO_SELECT);
  2631.         gPref.setCharPref(PREF_GENERAL_SKINS_SELECTEDSKIN, toSelect);
  2632.         gPref.clearUserPref(PREF_DSS_SWITCHPENDING);
  2633.         gPref.clearUserPref(PREF_DSS_SKIN_TO_SELECT);
  2634.       }
  2635.     }
  2636.     catch (e) {
  2637.     }
  2638.  
  2639.     if ("nsICrashReporter" in Ci && gApp instanceof Ci.nsICrashReporter) {
  2640.       // Annotate the crash report with the list of add-ons
  2641.       try {
  2642.         try {
  2643.           gApp.annotateCrashReport("Add-ons", gPref.getCharPref(PREF_EM_ENABLED_ITEMS));
  2644.         } catch (e) { }
  2645.         gApp.annotateCrashReport("Theme", gPref.getCharPref(PREF_GENERAL_SKINS_SELECTEDSKIN));
  2646.       }
  2647.       catch (ex) {
  2648.         // This will fail in unnofficial builds, ignorable error
  2649.       }
  2650.     }
  2651.  
  2652.     gLoggingEnabled = getPref("getBoolPref", PREF_EM_LOGGING_ENABLED, false);
  2653.     gCheckCompatibility = getPref("getBoolPref", PREF_EM_CHECK_COMPATIBILITY, true);
  2654.     gCheckUpdateSecurity = getPref("getBoolPref", PREF_EM_CHECK_UPDATE_SECURITY, true);
  2655.     gPref.addObserver("extensions.", this, false);
  2656.     gPref.addObserver(PREF_MATCH_OS_LOCALE, this, false);
  2657.     gPref.addObserver(PREF_SELECTED_LOCALE, this, false);
  2658.     this._updateLocale();
  2659.   },
  2660.  
  2661.   /**
  2662.    * Notify user that there are new addons updates
  2663.    */
  2664.   _showUpdatesWindow: function() {
  2665.     if (!getPref("getBoolPref", PREF_UPDATE_NOTIFYUSER, false))
  2666.       return;
  2667.  
  2668.     const EMURL = "chrome://mozapps/content/extensions/extensions.xul";
  2669.     const EMFEATURES = "chrome,centerscreen,extra-chrome,dialog,resizable,modal";
  2670.  
  2671.     var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
  2672.              getService(Ci.nsIWindowWatcher);
  2673.     var param = Cc["@mozilla.org/supports-array;1"].
  2674.                 createInstance(Ci.nsISupportsArray);
  2675.     var arg = Cc["@mozilla.org/supports-string;1"].
  2676.               createInstance(Ci.nsISupportsString);
  2677.     arg.data = "updates-only";
  2678.     param.AppendElement(arg);
  2679.     ww.openWindow(null, EMURL, null, EMFEATURES, param);
  2680.   },
  2681.  
  2682.   /**
  2683.    * Clean up on application shutdown to avoid leaks.
  2684.    */
  2685.   _shutdown: function() {
  2686.     gOS.removeObserver(this, "xpcom-shutdown");
  2687.  
  2688.     // Release strongly held services.
  2689.     gOS = null;
  2690.     if (this._ptr && gRDF) {
  2691.       gRDF.UnregisterDataSource(this._ptr);
  2692.       this._ptr = null;
  2693.     }
  2694.     gRDF = null;
  2695.     if (gPref) {
  2696.       gPref.removeObserver("extensions.", this);
  2697.       gPref.removeObserver(PREF_MATCH_OS_LOCALE, this);
  2698.       gPref.removeObserver(PREF_SELECTED_LOCALE, this);
  2699.     }
  2700.     gPref = null;
  2701.     gConsole = null;
  2702.     gVersionChecker = null;
  2703.     gInstallManifestRoot = null;
  2704.     gApp = null;
  2705.   },
  2706.  
  2707.   /**
  2708.    * Check for presence of critical Extension system files. If any is missing,
  2709.    * delete the others and signal that the system needs to rebuild them all
  2710.    * from scratch.
  2711.    * @returns true if any critical file is missing and the system needs to
  2712.    *          be rebuilt, false otherwise.
  2713.    */
  2714.   _ensureDatasetIntegrity: function () {
  2715.     var extensionsDS = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS]);
  2716.     var extensionsINI = getFile(KEY_PROFILEDIR, [FILE_EXTENSION_MANIFEST]);
  2717.     var extensionsCache = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS_STARTUP_CACHE]);
  2718.  
  2719.     var dsExists = extensionsDS.exists();
  2720.     var iniExists = extensionsINI.exists();
  2721.     var cacheExists = extensionsCache.exists();
  2722.  
  2723.     if (dsExists && iniExists && cacheExists)
  2724.       return false;
  2725.  
  2726.     // If any of the files are missing, remove the .ini file
  2727.     if (iniExists)
  2728.       extensionsINI.remove(false);
  2729.  
  2730.     // If the extensions datasource is missing remove the .cache file if it exists
  2731.     if (!dsExists && cacheExists)
  2732.       extensionsCache.remove(false);
  2733.  
  2734.     return true;
  2735.   },
  2736.  
  2737.   /**
  2738.    * See nsIExtensionManager.idl
  2739.    */
  2740.   start: function(commandLine) {
  2741.     var isDirty = false;
  2742.     var forceAutoReg = false;
  2743.  
  2744.     // Somehow the component list went away, and for that reason the new one
  2745.     // generated by this function is going to result in a different compreg.
  2746.     // We must force a restart.
  2747.     var componentList = getFile(KEY_PROFILEDIR, [FILE_EXTENSION_MANIFEST]);
  2748.     if (!componentList.exists())
  2749.       forceAutoReg = true;
  2750.  
  2751.     // Check for missing manifests - e.g. missing extensions.ini, missing
  2752.     // extensions.cache, extensions.rdf etc. If any of these files
  2753.     // is missing then we are in some kind of weird or initial state and need
  2754.     // to force a regeneration.
  2755.     if (this._ensureDatasetIntegrity())
  2756.       isDirty = true;
  2757.  
  2758.     // Configure any items that are being installed, uninstalled or upgraded
  2759.     // by being added, removed or modified by another process. We must do this
  2760.     // on every startup since there is no way we can tell if this has happened
  2761.     // or not!
  2762.     if (this._checkForFileChanges())
  2763.       isDirty = true;
  2764.  
  2765.     this._showUpdatesWindow();
  2766.  
  2767.     if (PendingOperations.size != 0)
  2768.       isDirty = true;
  2769.  
  2770.     // Extension Changes
  2771.     if (isDirty) {
  2772.       var needsRestart = this._finishOperations();
  2773.  
  2774.       if (forceAutoReg) {
  2775.         this._extensionListChanged = true;
  2776.         needsRestart = true;
  2777.       }
  2778.       return needsRestart;
  2779.     }
  2780.  
  2781.     this._startTimers();
  2782.  
  2783.     return false;
  2784.   },
  2785.  
  2786.   /**
  2787.    * Begins all background update check timers
  2788.    */
  2789.   _startTimers: function() {
  2790.     // Register a background update check timer
  2791.     var tm = Cc["@mozilla.org/updates/timer-manager;1"].
  2792.              getService(Ci.nsIUpdateTimerManager);
  2793.     var interval = getPref("getIntPref", PREF_EM_UPDATE_INTERVAL, 86400);
  2794.     tm.registerTimer("addon-background-update-timer", this, interval);
  2795.   },
  2796.  
  2797.   /**
  2798.    * Notified when a timer fires
  2799.    * @param   timer
  2800.    *          The timer that fired
  2801.    */
  2802.   notify: function(timer) {
  2803.     if (!getPref("getBoolPref", PREF_EM_UPDATE_ENABLED, true))
  2804.       return;
  2805.  
  2806.     var items = this.getItemList(Ci.nsIUpdateItem.TYPE_ANY, { });
  2807.  
  2808.     var updater = new ExtensionItemUpdater(this);
  2809.     updater.checkForUpdates(items, items.length,
  2810.                             Ci.nsIExtensionManager.UPDATE_CHECK_NEWVERSION,
  2811.                             new BackgroundUpdateCheckListener(this.datasource));
  2812.   },
  2813.  
  2814.   /**
  2815.    * See nsIExtensionManager.idl
  2816.    */
  2817.   handleCommandLineArgs: function(commandLine) {
  2818.     try {
  2819.       var globalExtension = commandLine.handleFlagWithParam("install-global-extension", false);
  2820.       if (globalExtension) {
  2821.         var file = commandLine.resolveFile(globalExtension);
  2822.         this._installGlobalItem(file);
  2823.       }
  2824.       var globalTheme = commandLine.handleFlagWithParam("install-global-theme", false);
  2825.       if (globalTheme) {
  2826.         file = commandLine.resolveFile(globalTheme);
  2827.         this._installGlobalItem(file);
  2828.       }
  2829.     }
  2830.     catch (e) {
  2831.       ERROR("ExtensionManager:handleCommandLineArgs - failure, catching exception - lineno: " +
  2832.             e.lineNumber + " - file: " + e.fileName + " - " + e);
  2833.     }
  2834.     commandLine.preventDefault = true;
  2835.   },
  2836.  
  2837.   /**
  2838.    * Installs an XPI/JAR file into the KEY_APP_GLOBAL install location.
  2839.    * @param   file
  2840.    *          The XPI/JAR file to extract
  2841.    */
  2842.   _installGlobalItem: function(file) {
  2843.     if (!file || !file.exists())
  2844.       throw new Error("Unable to find the file specified on the command line!");
  2845. //@line 2824 "e:\builds\tinderbox\XR-Trunk\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  2846.     // make sure the file is local on Windows
  2847.     file.normalize();
  2848.     if (file.path[1] != ':')
  2849.       throw new Error("Can't install global chrome from non-local file "+file.path);
  2850. //@line 2829 "e:\builds\tinderbox\XR-Trunk\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  2851.     var installManifestFile = extractRDFFileToTempDir(file, FILE_INSTALL_MANIFEST, true);
  2852.     if (!installManifestFile.exists())
  2853.       throw new Error("The package is missing an install manifest!");
  2854.     var installManifest = getInstallManifest(installManifestFile);
  2855.     installManifestFile.remove(false);
  2856.     var installData = this._getInstallData(installManifest);
  2857.     var installer = new Installer(installManifest, installData.id,
  2858.                                   InstallLocations.get(KEY_APP_GLOBAL),
  2859.                                   installData.type);
  2860.     installer._installExtensionFiles(file);
  2861.     if (installData.type == Ci.nsIUpdateItem.TYPE_THEME)
  2862.       installer.upgradeThemeChrome();
  2863.     else
  2864.       installer.upgradeExtensionChrome();
  2865.   },
  2866.  
  2867.   /**
  2868.    * Check to see if a file is a XPI/JAR file that the user dropped into this
  2869.    * Install Location. (i.e. a XPI that is not a staged XPI from an install
  2870.    * transaction that is currently in operation).
  2871.    * @param   file
  2872.    *          The XPI/JAR file to configure
  2873.    * @param   location
  2874.    *          The Install Location where this file was found.
  2875.    * @returns A nsIUpdateItem representing the dropped XPI if this file was a
  2876.    *          XPI/JAR that needs installation, null otherwise.
  2877.    */
  2878.   _getItemForDroppedFile: function(file, location) {
  2879.     if (fileIsItemPackage(file)) {
  2880.       // We know nothing about this item, it is not something we've
  2881.       // staged in preparation for finalization, so assume it's something
  2882.       // the user dropped in.
  2883.       LOG("A Item Package appeared at: " + file.path + " that we know " +
  2884.           "nothing about, assuming it was dropped in by the user and " +
  2885.           "configuring for installation now. Location Key: " + location.name);
  2886.  
  2887.       var installManifestFile = extractRDFFileToTempDir(file, FILE_INSTALL_MANIFEST, true);
  2888.       if (!installManifestFile.exists())
  2889.         return null;
  2890.       var installManifest = getInstallManifest(installManifestFile);
  2891.       installManifestFile.remove(false);
  2892.       var ds = this.datasource;
  2893.       var installData = this._getInstallData(installManifest);
  2894.       var targetAppInfo = ds.getTargetApplicationInfo(installData.id, installManifest);
  2895.       return makeItem(installData.id,
  2896.                       installData.version,
  2897.                       location.name,
  2898.                       targetAppInfo ? targetAppInfo.minVersion : "",
  2899.                       targetAppInfo ? targetAppInfo.maxVersion : "",
  2900.                       getManifestProperty(installManifest, "name"),
  2901.                       "", /* XPI Update URL */
  2902.                       "", /* XPI Update Hash */
  2903.                       getManifestProperty(installManifest, "iconURL"),
  2904.                       getManifestProperty(installManifest, "updateURL"),
  2905.                       getManifestProperty(installManifest, "updateKey"),
  2906.                       installData.type,
  2907.                       targetAppInfo ? targetAppInfo.appID : gApp.ID);
  2908.     }
  2909.     return null;
  2910.   },
  2911.  
  2912.   /**
  2913.    * Configure an item that was installed or upgraded by another process
  2914.    * so that |_finishOperations| can properly complete processing and
  2915.    * registration.
  2916.    * As this is the only point at which we can reliably know the Install
  2917.    * Location of this item, we use this as an opportunity to:
  2918.    * 1. Check that this item is compatible with this Firefox version.
  2919.    * 2. If it is, configure the item by using the supplied callback.
  2920.    *    We do not do any special handling in the case that the item is
  2921.    *    not compatible with this version other than to simply not register
  2922.    *    it and log that fact - there is no "phone home" check for updates.
  2923.    *    It may or may not make sense to do this, but for now we'll just
  2924.    *    not register.
  2925.    * @param   id
  2926.    *          The GUID of the item to validate and configure.
  2927.    * @param   location
  2928.    *          The Install Location where this item is installed.
  2929.    * @param   callback
  2930.    *          The callback that configures the item for installation upon
  2931.    *          successful validation.
  2932.    */
  2933.    installItem: function(id, location, callback) {
  2934.     // As this is the only pint at which we reliably know the installation
  2935.     var installRDF = location.getItemFile(id, FILE_INSTALL_MANIFEST);
  2936.     if (installRDF.exists()) {
  2937.       LOG("Item Installed/Upgraded at Install Location: " + location.name +
  2938.           " Item ID: " + id + ", attempting to register...");
  2939.       var installManifest = getInstallManifest(installRDF);
  2940.       var installData = this._getInstallData(installManifest);
  2941.       if (installData.error == INSTALLERROR_SUCCESS) {
  2942.         LOG("... success, item is compatible");
  2943.         callback(installManifest, installData.id, location, installData.type);
  2944.       }
  2945.       else if (installData.error == INSTALLERROR_INCOMPATIBLE_VERSION) {
  2946.         LOG("... success, item installed but is not compatible");
  2947.         callback(installManifest, installData.id, location, installData.type);
  2948.         this._appDisableItem(id);
  2949.       }
  2950.       else if (installData.error == INSTALLERROR_INSECURE_UPDATE) {
  2951.         LOG("... success, item installed but does not provide updates securely");
  2952.         callback(installManifest, installData.id, location, installData.type);
  2953.         this._appDisableItem(id);
  2954.       }
  2955.       else if (installData.error == INSTALLERROR_BLOCKLISTED) {
  2956.         LOG("... success, item installed but is blocklisted");
  2957.         callback(installManifest, installData.id, location, installData.type);
  2958.         this._appDisableItem(id);
  2959.       }
  2960.       else {
  2961.         /**
  2962.          * Turns an error code into a message for logging
  2963.          * @param   error
  2964.          *          an Install Error code
  2965.          * @returns A string message to be logged.
  2966.          */
  2967.         function translateErrorMessage(error) {
  2968.           switch (error) {
  2969.           case INSTALLERROR_INVALID_GUID:
  2970.             return "Invalid GUID";
  2971.           case INSTALLERROR_INVALID_VERSION:
  2972.             return "Invalid Version";
  2973.           case INSTALLERROR_INCOMPATIBLE_PLATFORM:
  2974.             return "Incompatible Platform";
  2975.           }
  2976.         }
  2977.         LOG("... failure, item is not compatible, error: " +
  2978.             translateErrorMessage(installData.error));
  2979.  
  2980.         // Add the item to the Startup Cache anyway, so we don't re-detect it
  2981.         // every time the app starts.
  2982.         StartupCache.put(location, id, OP_NONE, true);
  2983.       }
  2984.     }
  2985.   },
  2986.  
  2987.   /**
  2988.    * Check for changes to items that were made independently of the Extension
  2989.    * Manager, e.g. items were added or removed from a Install Location or items
  2990.    * in an Install Location changed.
  2991.    */
  2992.   _checkForFileChanges: function() {
  2993.     var em = this;
  2994.  
  2995.     /**
  2996.      * Determines if an item can be used based on whether or not the install
  2997.      * location of the "item" has an equal or higher priority than the install
  2998.      * location where another version may live.
  2999.      * @param   id
  3000.      *          The GUID of the item being installed.
  3001.      * @param   location
  3002.      *          The location where an item is to be installed.
  3003.      * @returns true if the item can be installed at that location, false
  3004.      *          otherwise.
  3005.      */
  3006.     function canUse(id, location) {
  3007.       for (var locationKey in StartupCache.entries) {
  3008.         if (locationKey != location.name &&
  3009.             id in StartupCache.entries[locationKey]) {
  3010.           if (StartupCache.entries[locationKey][id]) {
  3011.             var oldInstallLocation = InstallLocations.get(locationKey);
  3012.             if (oldInstallLocation.priority <= location.priority)
  3013.               return false;
  3014.           }
  3015.         }
  3016.       }
  3017.       return true;
  3018.     }
  3019.  
  3020.     /**
  3021.       * Gets a Dialog Param Block loaded with a set of strings to initialize the
  3022.       * XPInstall Confirmation Dialog.
  3023.       * @param   strings
  3024.       *          An array of strings
  3025.       * @returns A nsIDialogParamBlock loaded with the strings and dialog state.
  3026.       */
  3027.     function getParamBlock(strings) {
  3028.       var dpb = Cc["@mozilla.org/embedcomp/dialogparam;1"].
  3029.                 createInstance(Ci.nsIDialogParamBlock);
  3030.       // OK and Cancel Buttons
  3031.       dpb.SetInt(0, 2);
  3032.       // Number of Strings
  3033.       dpb.SetInt(1, strings.length);
  3034.       dpb.SetNumberStrings(strings.length);
  3035.       // Add Strings
  3036.       for (var i = 0; i < strings.length; ++i)
  3037.         dpb.SetString(i, strings[i]);
  3038.  
  3039.       var supportsString = Cc["@mozilla.org/supports-string;1"].
  3040.                            createInstance(Ci.nsISupportsString);
  3041.       var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  3042.       supportsString.data = bundle.GetStringFromName("droppedInWarning");
  3043.       var objs = Cc["@mozilla.org/array;1"].
  3044.                  createInstance(Ci.nsIMutableArray);
  3045.       objs.appendElement(supportsString, false);
  3046.       dpb.objects = objs;
  3047.       return dpb;
  3048.     }
  3049.  
  3050.     /**
  3051.      * Installs a set of files which were dropped into an install location by
  3052.      * the user, only after user confirmation.
  3053.      * @param   droppedInFiles
  3054.      *          An array of JS objects with the following properties:
  3055.      *          "file"      The nsILocalFile where the XPI lives
  3056.      *          "location"  The Install Location where the XPI was found.
  3057.      * @param   xpinstallStrings
  3058.      *          An array of strings used to initialize the XPInstall Confirm
  3059.      *          dialog.
  3060.      */
  3061.     function installDroppedInFiles(droppedInFiles, xpinstallStrings) {
  3062.       if (droppedInFiles.length == 0)
  3063.         return;
  3064.  
  3065.       var dpb = getParamBlock(xpinstallStrings);
  3066.       var ifptr = Cc["@mozilla.org/supports-interface-pointer;1"].
  3067.                   createInstance(Ci.nsISupportsInterfacePointer);
  3068.       ifptr.data = dpb;
  3069.       ifptr.dataIID = Ci.nsIDialogParamBlock;
  3070.       var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
  3071.                getService(Ci.nsIWindowWatcher);
  3072.       ww.openWindow(null, URI_XPINSTALL_CONFIRM_DIALOG,
  3073.                     "", "chrome,centerscreen,modal,dialog,titlebar", ifptr);
  3074.       if (!dpb.GetInt(0)) {
  3075.         // User said OK - install items
  3076.         for (var i = 0; i < droppedInFiles.length; ++i) {
  3077.           em.installItemFromFile(droppedInFiles[i].file,
  3078.                                  droppedInFiles[i].location.name);
  3079.           // We are responsible for cleaning up this file
  3080.           droppedInFiles[i].file.remove(false);
  3081.         }
  3082.       }
  3083.       else {
  3084.         for (i = 0; i < droppedInFiles.length; ++i) {
  3085.           // We are responsible for cleaning up this file
  3086.           droppedInFiles[i].file.remove(false);
  3087.         }
  3088.       }
  3089.     }
  3090.  
  3091.     var isDirty = false;
  3092.     var ignoreMTimeChanges = getPref("getBoolPref", PREF_EM_IGNOREMTIMECHANGES,
  3093.                                      false);
  3094.     StartupCache.read();
  3095.  
  3096.     // Array of objects with 'location' and 'id' properties to maybe install.
  3097.     var newItems = [];
  3098.  
  3099.     var droppedInFiles = [];
  3100.     var xpinstallStrings = [];
  3101.  
  3102.     // Enumerate over the install locations from low to high priority.  The
  3103.     // enumeration returned is pre-sorted.
  3104.     var installLocations = this.installLocations;
  3105.     while (installLocations.hasMoreElements()) {
  3106.       var location = installLocations.getNext().QueryInterface(Ci.nsIInstallLocation);
  3107.  
  3108.       // Hash the set of items actually held by the Install Location.
  3109.       var actualItems = { };
  3110.       var entries = location.itemLocations;
  3111.       while (true) {
  3112.         var entry = entries.nextFile;
  3113.         if (!entry)
  3114.           break;
  3115.  
  3116.         // Is this location a valid item? It must be a directory, and contain
  3117.         // an install.rdf manifest:
  3118.         if (entry.isDirectory()) {
  3119.           var installRDF = entry.clone();
  3120.           installRDF.append(FILE_INSTALL_MANIFEST);
  3121.  
  3122.           var id = location.getIDForLocation(entry);
  3123.           if (!id || (!installRDF.exists() &&
  3124.                       !location.itemIsManagedIndependently(id)))
  3125.             continue;
  3126.  
  3127.           actualItems[id] = entry;
  3128.         }
  3129.         else {
  3130.           // Check to see if this file is a XPI/JAR dropped into this dir
  3131.           // by the user, installing it if necessary. We do this here rather
  3132.           // than separately in |_finishOperations| because I don't want to
  3133.           // walk these lists multiple times on every startup.
  3134.           var item = this._getItemForDroppedFile(entry, location);
  3135.           if (item) {
  3136.             droppedInFiles.push({ file: entry, location: location });
  3137.             var prettyName = "";
  3138.             try {
  3139.               var zipReader = getZipReaderForFile(entry);
  3140.               var principal = { };
  3141.               var certPrincipal = zipReader.getCertificatePrincipal(null, principal);
  3142.               // XXXbz This string could be empty.  This needs better
  3143.               // UI to present principal.value.certificate's subject.
  3144.               prettyName = principal.value.prettyName;
  3145.             }
  3146.             catch (e) { }
  3147.             if (zipReader)
  3148.               zipReader.close();
  3149.             xpinstallStrings = xpinstallStrings.concat([item.name,
  3150.                                                         getURLSpecFromFile(entry),
  3151.                                                         item.iconURL,
  3152.                                                         prettyName]);
  3153.             isDirty = true;
  3154.           }
  3155.         }
  3156.       }
  3157.  
  3158.       if (location.name in StartupCache.entries) {
  3159.         // Look for items that have been uninstalled by removing their directory.
  3160.         for (var id in StartupCache.entries[location.name]) {
  3161.           if (!StartupCache.entries[location.name] ||
  3162.               !StartupCache.entries[location.name][id])
  3163.             continue;
  3164.  
  3165.           // Force _finishOperations to run if we have enabled or disabled items.
  3166.           // XXXdarin this should be unnecessary now that we check
  3167.           // PendingOperations.size in start()
  3168.           if (StartupCache.entries[location.name][id].op == OP_NEEDS_ENABLE ||
  3169.               StartupCache.entries[location.name][id].op == OP_NEEDS_DISABLE)
  3170.             isDirty = true;
  3171.  
  3172.           if (!(id in actualItems) &&
  3173.               StartupCache.entries[location.name][id].op != OP_NEEDS_UNINSTALL &&
  3174.               StartupCache.entries[location.name][id].op != OP_NEEDS_INSTALL &&
  3175.               StartupCache.entries[location.name][id].op != OP_NEEDS_UPGRADE) {
  3176.             // We have an entry for this id in the Extensions database, for this
  3177.             // install location, but it no longer exists in the Install Location.
  3178.             // We can infer from this that the item has been removed, so uninstall
  3179.             // it properly.
  3180.             if (canUse(id, location)) {
  3181.               LOG("Item Uninstalled via file removal from: " + StartupCache.entries[location.name][id].descriptor +
  3182.                   " Item ID: " + id + " Location Key: " + location.name + ", uninstalling item.");
  3183.  
  3184.               // Load the Extensions Datasource and force this item into the visible
  3185.               // items list if it is not already. This allows us to handle the case
  3186.               // where there is an entry for an item in the Startup Cache but not
  3187.               // in the extensions.rdf file - in that case the item will not be in
  3188.               // the visible list and calls to |getInstallLocation| will mysteriously
  3189.               // fail.
  3190.               this.datasource.updateVisibleList(id, location.name, false);
  3191.               this.uninstallItem(id);
  3192.               isDirty = true;
  3193.             }
  3194.           }
  3195.           else if (!ignoreMTimeChanges) {
  3196.             // Look for items whose mtime has changed, and as such we can assume
  3197.             // they have been "upgraded".
  3198.             var lf = { path: StartupCache.entries[location.name][id].descriptor };
  3199.             try {
  3200.                lf = getFileFromDescriptor(StartupCache.entries[location.name][id].descriptor, location);
  3201.             }
  3202.             catch (e) { }
  3203.  
  3204.             if (lf.exists && lf.exists()) {
  3205.               var actualMTime = Math.floor(lf.lastModifiedTime / 1000);
  3206.               if (actualMTime != StartupCache.entries[location.name][id].mtime) {
  3207.                 LOG("Item Location path changed: " + lf.path + " Item ID: " +
  3208.                     id + " Location Key: " + location.name + ", attempting to upgrade item...");
  3209.                 if (canUse(id, location)) {
  3210.                   this.installItem(id, location,
  3211.                                    function(installManifest, id, location, type) {
  3212.                                      em._upgradeItem(installManifest, id, location,
  3213.                                                      type);
  3214.                                    });
  3215.                   isDirty = true;
  3216.                 }
  3217.               }
  3218.             }
  3219.             else {
  3220.               isDirty = true;
  3221.               LOG("Install Location returned a missing or malformed item path! " +
  3222.                   "Item Path: " + lf.path + ", Location Key: " + location.name +
  3223.                   " Item ID: " + id);
  3224.               if (canUse(id, location)) {
  3225.                 // Load the Extensions Datasource and force this item into the visible
  3226.                 // items list if it is not already. This allows us to handle the case
  3227.                 // where there is an entry for an item in the Startup Cache but not
  3228.                 // in the extensions.rdf file - in that case the item will not be in
  3229.                 // the visible list and calls to |getInstallLocation| will mysteriously
  3230.                 // fail.
  3231.                 this.datasource.updateVisibleList(id, location.name, false);
  3232.                 this.uninstallItem(id);
  3233.               }
  3234.             }
  3235.           }
  3236.         }
  3237.       }
  3238.  
  3239.       // Look for items that have been installed by appearing in the location.
  3240.       for (var id in actualItems) {
  3241.         if (!(location.name in StartupCache.entries) ||
  3242.             !(id in StartupCache.entries[location.name]) ||
  3243.             !StartupCache.entries[location.name][id]) {
  3244.           // Remember that we've seen this item
  3245.           StartupCache.put(location, id, OP_NONE, true);
  3246.           // Push it on the stack of items to maybe install later
  3247.           newItems.push({location: location, id: id});
  3248.         }
  3249.       }
  3250.     }
  3251.  
  3252.     // Process any newly discovered items.  We do this here instead of in the
  3253.     // previous loop so that we can be sure that we have a fully populated
  3254.     // StartupCache.
  3255.     for (var i = 0; i < newItems.length; ++i) {
  3256.       var id = newItems[i].id;
  3257.       var location = newItems[i].location;
  3258.       if (canUse(id, location)) {
  3259.         LOG("Item Installed via directory addition to Install Location: " +
  3260.             location.name + " Item ID: " + id + ", attempting to register...");
  3261.         this.installItem(id, location,
  3262.                          function(installManifest, id, location, type) {
  3263.                            em._configureForthcomingItem(installManifest, id, location,
  3264.                                                         type);
  3265.                          });
  3266.         // Disable add-ons on install when the InstallDisabled file exists.
  3267.         // This is so Talkback will be disabled on a subset of installs.
  3268.         var installDisabled = location.getItemFile(id, "InstallDisabled");
  3269.         if (installDisabled.exists())
  3270.           em.disableItem(id);
  3271.         isDirty = true;
  3272.       }
  3273.     }
  3274.  
  3275.     // Ask the user if they want to install the dropped items, for security
  3276.     // purposes.
  3277.     installDroppedInFiles(droppedInFiles, xpinstallStrings);
  3278.  
  3279.     return isDirty;
  3280.   },
  3281.  
  3282.   /**
  3283.    * Upgrades contents.rdf files to chrome.manifest files for any existing
  3284.    * Extensions and Themes.
  3285.    * @returns true if actions were performed that require a restart, false
  3286.    *          otherwise.
  3287.    */
  3288.   _upgradeChrome: function() {
  3289.     if (inSafeMode())
  3290.       return false;
  3291.  
  3292.     var checkForNewChrome = false;
  3293.     var ds = this.datasource;
  3294.     // If we have extensions that were installed before the new flat chrome
  3295.     // manifests, and are still valid, we need to manually create the flat
  3296.     // manifest files.
  3297.     var extensions = this._getActiveItems(Ci.nsIUpdateItem.TYPE_EXTENSION +
  3298.                                           Ci.nsIUpdateItem.TYPE_LOCALE);
  3299.     for (var i = 0; i < extensions.length; ++i) {
  3300.       var e = extensions[i];
  3301.       var itemLocation = e.location.getItemLocation(e.id);
  3302.       var manifest = itemLocation.clone();
  3303.       manifest.append(FILE_CHROME_MANIFEST);
  3304.       if (!manifest.exists()) {
  3305.         var installRDF = itemLocation.clone();
  3306.         installRDF.append(FILE_INSTALL_MANIFEST);
  3307.         var installLocation = this.getInstallLocation(e.id);
  3308.         if (installLocation && installRDF.exists()) {
  3309.           var itemLocation = installLocation.getItemLocation(e.id);
  3310.           if (itemLocation.exists() && itemLocation.isDirectory()) {
  3311.             var installer = new Installer(ds, e.id, installLocation,
  3312.                                           Ci.nsIUpdateItem.TYPE_EXTENSION);
  3313.             installer.upgradeExtensionChrome();
  3314.           }
  3315.         }
  3316.         else {
  3317.           ds.removeItemMetadata(e.id);
  3318.           ds.removeItemFromContainer(e.id);
  3319.         }
  3320.  
  3321.         checkForNewChrome = true;
  3322.       }
  3323.     }
  3324.  
  3325.     var themes = this._getActiveItems(Ci.nsIUpdateItem.TYPE_THEME);
  3326.     // If we have themes that were installed before the new flat chrome
  3327.     // manifests, and are still valid, we need to manually create the flat
  3328.     // manifest files.
  3329.     for (i = 0; i < themes.length; ++i) {
  3330.       var item = themes[i];
  3331.       var itemLocation = item.location.getItemLocation(item.id);
  3332.       var manifest = itemLocation.clone();
  3333.       manifest.append(FILE_CHROME_MANIFEST);
  3334.       if (manifest.exists() ||
  3335.           item.id == stripPrefix(RDFURI_DEFAULT_THEME, PREFIX_ITEM_URI))
  3336.         continue;
  3337.  
  3338.       var entries;
  3339.       try {
  3340.         var manifestURI = getURIFromFile(manifest);
  3341.         var chromeDir = itemLocation.clone();
  3342.         chromeDir.append(DIR_CHROME);
  3343.  
  3344.         if (!chromeDir.exists() || !chromeDir.isDirectory()) {
  3345.           ds.removeItemMetadata(item.id);
  3346.           ds.removeItemFromContainer(item.id);
  3347.           continue;
  3348.         }
  3349.  
  3350.         // We're relying on the fact that there is only one JAR file
  3351.         // in the "chrome" directory. This is a hack, but it works.
  3352.         entries = chromeDir.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
  3353.         var jarFile = entries.nextFile;
  3354.         if (jarFile) {
  3355.           var jarFileURI = getURIFromFile(jarFile);
  3356.           var contentsURI = newURI("jar:" + jarFileURI.spec + "!/");
  3357.  
  3358.           // Use the Chrome Registry API to install the theme there
  3359.           var cr = Cc["@mozilla.org/chrome/chrome-registry;1"].
  3360.                    getService(Ci.nsIToolkitChromeRegistry);
  3361.           cr.processContentsManifest(contentsURI, manifestURI, contentsURI, false, true);
  3362.         }
  3363.         entries.close();
  3364.       }
  3365.       catch (e) {
  3366.         ERROR("_upgradeChrome: failed to upgrade contents manifest for " +
  3367.               "theme: " + item.id + ", exception: " + e + "... The theme will be " +
  3368.               "disabled.");
  3369.         this._appDisableItem(item.id);
  3370.       }
  3371.       finally {
  3372.         try {
  3373.           entries.close();
  3374.         }
  3375.         catch (e) {
  3376.         }
  3377.       }
  3378.       checkForNewChrome = true;
  3379.     }
  3380.     return checkForNewChrome;
  3381.   },
  3382.  
  3383.   _checkForUncoveredItem: function(id) {
  3384.     var ds = this.datasource;
  3385.     var oldLocation = this.getInstallLocation(id);
  3386.     var newLocations = [];
  3387.     for (var locationKey in StartupCache.entries) {
  3388.       var location = InstallLocations.get(locationKey);
  3389.       if (id in StartupCache.entries[locationKey] &&
  3390.           location.priority > oldLocation.priority)
  3391.         newLocations.push(location);
  3392.     }
  3393.     newLocations.sort(function(a, b) { return b.priority - a.priority; });
  3394.     if (newLocations.length > 0) {
  3395.       for (var i = 0; i < newLocations.length; ++i) {
  3396.         // Check to see that the item at the location exists
  3397.         var installRDF = newLocations[i].getItemFile(id, FILE_INSTALL_MANIFEST);
  3398.         if (installRDF.exists()) {
  3399.           // Update the visible item cache so that |_finalizeUpgrade| is properly
  3400.           // called from |_finishOperations|
  3401.           var name = newLocations[i].name;
  3402.           ds.updateVisibleList(id, name, true);
  3403.           PendingOperations.addItem(OP_NEEDS_UPGRADE,
  3404.                                     { locationKey: name, id: id });
  3405.           PendingOperations.addItem(OP_NEEDS_INSTALL,
  3406.                                     { locationKey: name, id: id });
  3407.           break;
  3408.         }
  3409.         else {
  3410.           // If no item exists at the location specified, remove this item
  3411.           // from the visible items list and check again.
  3412.           StartupCache.clearEntry(newLocations[i], id);
  3413.           ds.updateVisibleList(id, null, true);
  3414.         }
  3415.       }
  3416.     }
  3417.     else
  3418.       ds.updateVisibleList(id, null, true);
  3419.   },
  3420.  
  3421.   /**
  3422.    * Finish up pending operations - perform upgrades, installs, enables/disables,
  3423.    * uninstalls etc.
  3424.    * @returns true if actions were performed that require a restart, false
  3425.    *          otherwise.
  3426.    */
  3427.   _finishOperations: function() {
  3428.     try {
  3429.       // Stuff has changed, load the Extensions datasource in all its RDFey
  3430.       // glory.
  3431.       var ds = this.datasource;
  3432.       var updatedTargetAppInfos = [];
  3433.  
  3434.       var needsRestart = false;
  3435.       var upgrades = [];
  3436.       var newAddons = [];
  3437.       var addons = getPref("getCharPref", PREF_EM_NEW_ADDONS_LIST, "");
  3438.       if (addons != "")
  3439.         newAddons = addons.split(",");
  3440.       do {
  3441.         // Enable and disable during startup so items that are changed in the
  3442.         // ui can be reset to a no-op.
  3443.         // Look for extensions that need to be enabled.
  3444.         var items = PendingOperations.getOperations(OP_NEEDS_ENABLE);
  3445.         for (var i = items.length - 1; i >= 0; --i) {
  3446.           var id = items[i].id;
  3447.           var installLocation = this.getInstallLocation(id);
  3448.           StartupCache.put(installLocation, id, OP_NONE, true);
  3449.           PendingOperations.clearItem(OP_NEEDS_ENABLE, id);
  3450.           needsRestart = true;
  3451.         }
  3452.         PendingOperations.clearItems(OP_NEEDS_ENABLE);
  3453.  
  3454.         // Look for extensions that need to be disabled.
  3455.         items = PendingOperations.getOperations(OP_NEEDS_DISABLE);
  3456.         for (i = items.length - 1; i >= 0; --i) {
  3457.           id = items[i].id;
  3458.           installLocation = this.getInstallLocation(id);
  3459.           StartupCache.put(installLocation, id, OP_NONE, true);
  3460.           PendingOperations.clearItem(OP_NEEDS_DISABLE, id);
  3461.           needsRestart = true;
  3462.         }
  3463.         PendingOperations.clearItems(OP_NEEDS_DISABLE);
  3464.  
  3465.         // Look for extensions that need to be upgraded. The process here is to
  3466.         // uninstall the old version of the extension first, then install the
  3467.         // new version in its place.
  3468.         items = PendingOperations.getOperations(OP_NEEDS_UPGRADE);
  3469.         for (i = items.length - 1; i >= 0; --i) {
  3470.           id = items[i].id;
  3471.           var newLocation = InstallLocations.get(items[i].locationKey);
  3472.           // check if there is updated app compatibility info
  3473.           var newTargetAppInfo = ds.getUpdatedTargetAppInfo(id);
  3474.           if (newTargetAppInfo)
  3475.             updatedTargetAppInfos.push(newTargetAppInfo);
  3476.           this._finalizeUpgrade(id, newLocation);
  3477.           upgrades.push(id);
  3478.         }
  3479.         PendingOperations.clearItems(OP_NEEDS_UPGRADE);
  3480.  
  3481.         // Install items
  3482.         items = PendingOperations.getOperations(OP_NEEDS_INSTALL);
  3483.         for (i = items.length - 1; i >= 0; --i) {
  3484.           needsRestart = true;
  3485.           id = items[i].id;
  3486.           // check if there is updated app compatibility info
  3487.           newTargetAppInfo = ds.getUpdatedTargetAppInfo(id);
  3488.           if (newTargetAppInfo)
  3489.             updatedTargetAppInfos.push(newTargetAppInfo);
  3490.           this._finalizeInstall(id, null);
  3491.           if (upgrades.indexOf(id) < 0 && newAddons.indexOf(id) < 0)
  3492.             newAddons.push(id);
  3493.         }
  3494.         PendingOperations.clearItems(OP_NEEDS_INSTALL);
  3495.  
  3496.         // Look for extensions that need to be removed. This MUST be done after
  3497.         // the install operations since extensions to be installed may have to be
  3498.         // uninstalled if there are errors during the installation process!
  3499.         items = PendingOperations.getOperations(OP_NEEDS_UNINSTALL);
  3500.         for (i = items.length - 1; i >= 0; --i) {
  3501.           id = items[i].id;
  3502.           this._finalizeUninstall(id);
  3503.           this._checkForUncoveredItem(id);
  3504.           needsRestart = true;
  3505.           var pos = newAddons.indexOf(id);
  3506.           if (pos >= 0)
  3507.             newAddons.splice(pos, 1);
  3508.         }
  3509.         PendingOperations.clearItems(OP_NEEDS_UNINSTALL);
  3510.  
  3511.         // When there have been operations and all operations have completed.
  3512.         if (PendingOperations.size == 0) {
  3513.           // If there is updated app compatibility info update the datasource.
  3514.           for (i = 0; i < updatedTargetAppInfos.length; ++i)
  3515.             ds.setTargetApplicationInfo(updatedTargetAppInfos[i].id,
  3516.                                         updatedTargetAppInfos[i].targetAppID,
  3517.                                         updatedTargetAppInfos[i].minVersion,
  3518.                                         updatedTargetAppInfos[i].maxVersion,
  3519.                                         null);
  3520.  
  3521.           // Enumerate all items
  3522.           var ctr = getContainer(ds, ds._itemRoot);
  3523.           var elements = ctr.GetElements();
  3524.           while (elements.hasMoreElements()) {
  3525.             var itemResource = elements.getNext().QueryInterface(Ci.nsIRDFResource);
  3526.  
  3527.             // Ensure appDisabled is in the correct state.
  3528.             id = stripPrefix(itemResource.Value, PREFIX_ITEM_URI);
  3529.             if (this._isUsableItem(id))
  3530.               ds.setItemProperty(id, EM_R("appDisabled"), null);
  3531.             else
  3532.               ds.setItemProperty(id, EM_R("appDisabled"), EM_L("true"));
  3533.  
  3534.             // userDisabled is set based on its value being OP_NEEDS_ENABLE or
  3535.             // OP_NEEDS_DISABLE. This allows us to have an item to be enabled
  3536.             // by the app and disabled by the user during a single restart.
  3537.             var value = stringData(ds.GetTarget(itemResource, EM_R("userDisabled"), true));
  3538.             if (value == OP_NEEDS_ENABLE)
  3539.               ds.setItemProperty(id, EM_R("userDisabled"), null);
  3540.             else if (value == OP_NEEDS_DISABLE)
  3541.               ds.setItemProperty(id, EM_R("userDisabled"), EM_L("true"));
  3542.           }
  3543.         }
  3544.       }
  3545.       while (PendingOperations.size > 0);
  3546.  
  3547.       // Upgrade contents.rdf files to the new chrome.manifest format for
  3548.       // existing Extensions and Themes
  3549.       if (this._upgradeChrome()) {
  3550.         var cr = Cc["@mozilla.org/chrome/chrome-registry;1"].
  3551.                  getService(Ci.nsIChromeRegistry);
  3552.         cr.checkForNewChrome();
  3553.       }
  3554.  
  3555.       // If no additional restart is required, it implies that there are
  3556.       // no new components that need registering so we can inform the app
  3557.       // not to do any extra startup checking next time round.
  3558.       this._updateManifests(needsRestart);
  3559.  
  3560.       // Remember the list of add-ons that were installed this time around
  3561.       // unless this was a new profile.
  3562.       if (!gFirstRun && newAddons.length > 0)
  3563.         gPref.setCharPref(PREF_EM_NEW_ADDONS_LIST, newAddons.join(","));
  3564.     }
  3565.     catch (e) {
  3566.       ERROR("ExtensionManager:_finishOperations - failure, catching exception - lineno: " +
  3567.             e.lineNumber + " - file: " + e.fileName + " - " + e);
  3568.     }
  3569.     return needsRestart;
  3570.   },
  3571.  
  3572.   /**
  3573.    * Checks to see if there are items that are incompatible with this version
  3574.    * of the application, disables them to prevent incompatibility problems and
  3575.    * invokes the Update Wizard to look for newer versions.
  3576.    * @returns true if there were incompatible items installed and disabled, and
  3577.    *          the application must now be restarted to reinitialize XPCOM,
  3578.    *          false otherwise.
  3579.    */
  3580.   checkForMismatches: function() {
  3581.     // Check to see if the version of the application that is being started
  3582.     // now is the same one that was started last time.
  3583.     var currAppVersion = gApp.version;
  3584.     var lastAppVersion = getPref("getCharPref", PREF_EM_LAST_APP_VERSION, "");
  3585.     if (currAppVersion == lastAppVersion)
  3586.       return false;
  3587.     // With a new profile lastAppVersion doesn't exist yet.
  3588.     if (!lastAppVersion) {
  3589.       gPref.setCharPref(PREF_EM_LAST_APP_VERSION, currAppVersion);
  3590.       return false;
  3591.     }
  3592.  
  3593.     // Version mismatch, we have to load the extensions datasource and do
  3594.     // version checking. Time hit here doesn't matter since this doesn't happen
  3595.     // all that often.
  3596.     this._upgradeFromV10();
  3597.  
  3598.     // Make the extensions datasource consistent if it isn't already.
  3599.     var isDirty = false;
  3600.     if (this._ensureDatasetIntegrity())
  3601.       isDirty = true;
  3602.  
  3603.     if (this._checkForFileChanges())
  3604.       isDirty = true;
  3605.  
  3606.     if (PendingOperations.size != 0)
  3607.       isDirty = true;
  3608.  
  3609.     if (isDirty)
  3610.       this._finishOperations();
  3611.  
  3612.     var ds = this.datasource;
  3613.     // During app upgrade cleanup invalid entries in the extensions datasource.
  3614.     ds.beginUpdateBatch();
  3615.     var allResources = ds.GetAllResources();
  3616.     while (allResources.hasMoreElements()) {
  3617.       var res = allResources.getNext().QueryInterface(Ci.nsIRDFResource);
  3618.       if (ds.GetTarget(res, EM_R("downloadURL"), true) ||
  3619.           (!ds.GetTarget(res, EM_R("installLocation"), true) &&
  3620.           stringData(ds.GetTarget(res, EM_R("appDisabled"), true)) == "true"))
  3621.         ds.removeDownload(res.Value);
  3622.     }
  3623.     ds.endUpdateBatch();
  3624.  
  3625.     var badItems = [];
  3626.     var allAppManaged = true;
  3627.     var ctr = getContainer(ds, ds._itemRoot);
  3628.     var elements = ctr.GetElements();
  3629.     while (elements.hasMoreElements()) {
  3630.       var itemResource = elements.getNext().QueryInterface(Ci.nsIRDFResource);
  3631.       var id = stripPrefix(itemResource.Value, PREFIX_ITEM_URI);
  3632.       var location = this.getInstallLocation(id);
  3633.       if (!location) {
  3634.         // Item was in an unknown install location
  3635.         badItems.push(id);
  3636.         continue;
  3637.       }
  3638.  
  3639.       if (ds.getItemProperty(id, "appManaged") == "true") {
  3640.         // Force an update of the metadata for appManaged extensions since the
  3641.         // last modified time is not updated for directories on FAT / FAT32
  3642.         // filesystems when software update applies a new version of the app.
  3643.         if (location.name == KEY_APP_GLOBAL) {
  3644.           var installRDF = location.getItemFile(id, FILE_INSTALL_MANIFEST);
  3645.           if (installRDF.exists()) {
  3646.             var metadataDS = getInstallManifest(installRDF);
  3647.             ds.addItemMetadata(id, metadataDS, location);
  3648.             ds.updateProperty(id, "compatible");
  3649.           }
  3650.         }
  3651.       }
  3652.       else if (allAppManaged)
  3653.         allAppManaged = false;
  3654.  
  3655.       if (ds.getItemProperty(id, "providesUpdatesSecurely") == "false") {
  3656.         /* It's possible the previous version did not understand updateKeys so
  3657.          * check if we can import one for this addon from it's manifest. */
  3658.         installRDF = location.getItemFile(id, FILE_INSTALL_MANIFEST);
  3659.         if (installRDF.exists()) {
  3660.           metadataDS = getInstallManifest(installRDF);
  3661.           var literal = metadataDS.GetTarget(gInstallManifestRoot, EM_R("updateKey"), true);
  3662.           if (literal && literal instanceof Ci.nsIRDFLiteral)
  3663.             ds.setItemProperty(id, EM_R("updateKey"), literal);
  3664.         }
  3665.       }
  3666.  
  3667.       // appDisabled is determined by an item being compatible, using secure
  3668.       // updates, satisfying its dependencies, and not being blocklisted
  3669.       if (this._isUsableItem(id)) {
  3670.         if (ds.getItemProperty(id, "appDisabled"))
  3671.           ds.setItemProperty(id, EM_R("appDisabled"), null);
  3672.       }
  3673.       else if (!ds.getItemProperty(id, "appDisabled"))
  3674.         ds.setItemProperty(id, EM_R("appDisabled"), EM_L("true"));
  3675.  
  3676.       ds.setItemProperty(id, EM_R("availableUpdateURL"), null);
  3677.       ds.setItemProperty(id, EM_R("availableUpdateVersion"), null);
  3678.     }
  3679.  
  3680.     // Must clean up outside of the loop. Modifying the container while
  3681.     // iterating its contents is bad.
  3682.     for (var i = 0; i < badItems.length; i++) {
  3683.       id = badItems[i];
  3684.       LOG("Item " + id + " was installed in an unknown location, removing.");
  3685.       var disabled = ds.getItemProperty(id, "userDisabled") == "true";
  3686.       // Clean up the datasource
  3687.       ds.removeCorruptItem(id);
  3688.       // Check for any unhidden items.
  3689.       var entries = StartupCache.findEntries(id);
  3690.       if (entries.length > 0) {
  3691.         var newLocation = InstallLocations.get(entries[0].location);
  3692.         for (var j = 1; j < entries.length; j++) {
  3693.           location = InstallLocations.get(entries[j].location);
  3694.           if (newLocation.priority < location.priority)
  3695.             newLocation = location;
  3696.         }
  3697.         LOG("Activating item " + id + " in " + newLocation.name);
  3698.         var em = this;
  3699.         this.installItem(id, newLocation,
  3700.                          function(installManifest, id, location, type) {
  3701.                            em._configureForthcomingItem(installManifest, id, location,
  3702.                                                         type);
  3703.                          });
  3704.         if (disabled)
  3705.           em.disableItem(id);
  3706.       }
  3707.     }
  3708.  
  3709.     // Update the manifests to reflect the items that were disabled / enabled.
  3710.     this._updateManifests(true);
  3711.  
  3712.     // Always check for compatibility updates when upgrading if we have add-ons
  3713.     // that aren't managed by the application.
  3714.     if (!allAppManaged)
  3715.       this._showMismatchWindow();
  3716.  
  3717.     // Finish any pending upgrades from the compatibility update to avoid an
  3718.     // additional restart.
  3719.     if (PendingOperations.size != 0)
  3720.       this._finishOperations();
  3721.  
  3722.     // Update the last app version so we don't do this again with this version.
  3723.     gPref.setCharPref(PREF_EM_LAST_APP_VERSION, currAppVersion);
  3724.  
  3725.     // Prevent extension update dialog from showing
  3726.     gPref.setBoolPref(PREF_UPDATE_NOTIFYUSER, false);
  3727.     return true;
  3728.   },
  3729.  
  3730.   /**
  3731.    * Shows the "Compatibility Updates" UI
  3732.    */
  3733.   _showMismatchWindow: function(items) {
  3734.     var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
  3735.              getService(Ci.nsIWindowMediator);
  3736.     var wizard = wm.getMostRecentWindow("Update:Wizard");
  3737.     if (wizard)
  3738.       wizard.focus();
  3739.     else {
  3740.       var features = "chrome,centerscreen,dialog,titlebar,modal";
  3741.       // This *must* be modal so as not to break startup! This code is invoked before
  3742.       // the main event loop is initiated (via checkForMismatches).
  3743.       var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
  3744.                getService(Ci.nsIWindowWatcher);
  3745.       ww.openWindow(null, URI_EXTENSION_UPDATE_DIALOG, "", features, null);
  3746.     }
  3747.   },
  3748.  
  3749.   /*
  3750.    * Catch all for facilitating a version 1.0 profile upgrade.
  3751.    * 1) removes the abandoned default theme directory from the profile.
  3752.    * 2) prepares themes installed with version 1.0 for installation.
  3753.    * 3) initiates an install to populate the new extensions datasource.
  3754.    * 4) migrates the disabled attribute from the old datasource.
  3755.    * 5) migrates the app compatibility info from the old datasource.
  3756.    */
  3757.   _upgradeFromV10: function() {
  3758.     var extensionsDS = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS]);
  3759.     var dsExists = extensionsDS.exists();
  3760.     // Toolkiit 1.7 profiles (Firefox 1.0, Thunderbird 1.0, etc.) have a default
  3761.     // theme directory in the profile's extensions directory that will be
  3762.     // disabled due to having a maxVersion that is incompatible with the
  3763.     // toolkit 1.8 release of the app.
  3764.     var profileDefaultTheme = getDirNoCreate(KEY_PROFILEDS, [DIR_EXTENSIONS,
  3765.                                              stripPrefix(RDFURI_DEFAULT_THEME, PREFIX_ITEM_URI)]);
  3766.     if (profileDefaultTheme && profileDefaultTheme.exists()) {
  3767.       removeDirRecursive(profileDefaultTheme);
  3768.       // Sunbird 0.3a1 didn't move the default theme into the app's extensions
  3769.       // directory and we can't install it while uninstalling the one in the
  3770.       // profile directory. If we have a toolkit 1.8 extensions datasource and
  3771.       // a profile default theme deleting the toolkit 1.8 extensions datasource
  3772.       // will fix this problem when the datasource is re-created.
  3773.       if (dsExists)
  3774.         extensionsDS.remove(false);
  3775.     }
  3776.  
  3777.     // return early if the toolkit 1.7 extensions datasource file doesn't exist.
  3778.     var oldExtensionsFile = getFile(KEY_PROFILEDIR, [DIR_EXTENSIONS, "Extensions.rdf"]);
  3779.     if (!oldExtensionsFile.exists())
  3780.       return;
  3781.  
  3782.     // Sunbird 0.2 used a different GUID for the default theme
  3783.     profileDefaultTheme = getDirNoCreate(KEY_PROFILEDS, [DIR_EXTENSIONS,
  3784.                                          "{8af2d0a7-e394-4de2-ae55-2dae532a7a9b}"]);
  3785.     if (profileDefaultTheme && profileDefaultTheme.exists())
  3786.       removeDirRecursive(profileDefaultTheme);
  3787.  
  3788.     // Firefox 0.9 profiles may have DOMi 1.0 with just an install.rdf
  3789.     var profileDOMi = getDirNoCreate(KEY_PROFILEDS, [DIR_EXTENSIONS,
  3790.                                      "{641d8d09-7dda-4850-8228-ac0ab65e2ac9}"]);
  3791.     if (profileDOMi && profileDOMi.exists())
  3792.       removeDirRecursive(profileDOMi);
  3793.  
  3794.     // return early to avoid migrating data twice if we already have a
  3795.     // toolkit 1.8 extension datasource.
  3796.     if (dsExists)
  3797.       return;
  3798.  
  3799.     // Prepare themes for installation
  3800.     // Only enumerate directories in the app-profile and app-global locations.
  3801.     var locations = [KEY_APP_PROFILE, KEY_APP_GLOBAL];
  3802.     for (var i = 0; i < locations.length; ++i) {
  3803.       var location = InstallLocations.get(locations[i]);
  3804.       if (!location.canAccess)
  3805.         continue;
  3806.  
  3807.       var entries = location.itemLocations;
  3808.       var entry;
  3809.       while ((entry = entries.nextFile)) {
  3810.         var installRDF = entry.clone();
  3811.         installRDF.append(FILE_INSTALL_MANIFEST);
  3812.  
  3813.         var chromeDir = entry.clone();
  3814.         chromeDir.append(DIR_CHROME);
  3815.  
  3816.         // It must be a directory without an install.rdf and it must contain
  3817.         // a chrome directory
  3818.         if (!entry.isDirectory() || installRDF.exists() || !chromeDir.exists())
  3819.           continue;
  3820.  
  3821.         var chromeEntries = chromeDir.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
  3822.         if (!chromeEntries.hasMoreElements())
  3823.           continue;
  3824.  
  3825.         // We're relying on the fact that there is only one JAR file
  3826.         // in the "chrome" directory. This is a hack, but it works.
  3827.         var jarFile = chromeEntries.nextFile;
  3828.         if (jarFile.isDirectory())
  3829.           continue;
  3830.         var id = location.getIDForLocation(entry);
  3831.  
  3832.         try {
  3833.           var zipReader = getZipReaderForFile(jarFile);
  3834.           zipReader.extract(FILE_INSTALL_MANIFEST, installRDF);
  3835.  
  3836.           var contentsManifestFile = location.getItemFile(id, FILE_CONTENTS_MANIFEST);
  3837.           zipReader.extract(FILE_CONTENTS_MANIFEST, contentsManifestFile);
  3838.  
  3839.           var rootFiles = ["preview.png", "icon.png"];
  3840.           for (var i = 0; i < rootFiles.length; ++i) {
  3841.             try {
  3842.               var target = location.getItemFile(id, rootFiles[i]);
  3843.               zipReader.extract(rootFiles[i], target);
  3844.             }
  3845.             catch (e) {
  3846.             }
  3847.           }
  3848.           zipReader.close();
  3849.         }
  3850.         catch (e) {
  3851.           ERROR("ExtensionManager:_upgradeFromV10 - failed to extract theme files\r\n" +
  3852.                 "Exception: " + e);
  3853.         }
  3854.       }
  3855.     }
  3856.  
  3857.     // When upgrading from a version 1.0 profile we need to populate the
  3858.     // extensions datasource with all items before checking for incompatible
  3859.     // items since the datasource hasn't been created yet.
  3860.     var itemsToCheck = [];
  3861.     if (this._checkForFileChanges()) {
  3862.       // Create a list of all items that are to be installed so we can migrate
  3863.       // these items's settings to the new datasource.
  3864.       var items = PendingOperations.getOperations(OP_NEEDS_INSTALL);
  3865.       for (i = items.length - 1; i >= 0; --i) {
  3866.         if (items[i].locationKey == KEY_APP_PROFILE ||
  3867.             items[i].locationKey == KEY_APP_GLOBAL)
  3868.           itemsToCheck.push(items[i].id);
  3869.       }
  3870.       this._finishOperations();
  3871.     }
  3872.  
  3873.     // If there are no items to migrate settings for return early.
  3874.     if (itemsToCheck.length == 0)
  3875.       return;
  3876.  
  3877.     var fileURL = getURLSpecFromFile(oldExtensionsFile);
  3878.     var oldExtensionsDS = gRDF.GetDataSourceBlocking(fileURL);
  3879.     var versionChecker = getVersionChecker();
  3880.     var ds = this.datasource;
  3881.     var currAppVersion = gApp.version;
  3882.     var currAppID = gApp.ID;
  3883.     for (var i = 0; i < itemsToCheck.length; ++i) {
  3884.       var item = ds.getItemForID(itemsToCheck[i]);
  3885.       var oldPrefix = (item.type == Ci.nsIUpdateItem.TYPE_EXTENSION) ? PREFIX_EXTENSION : PREFIX_THEME;
  3886.       var oldRes = gRDF.GetResource(oldPrefix + item.id);
  3887.       // Disable the item if it was disabled in the version 1.0 extensions
  3888.       // datasource.
  3889.       if (oldExtensionsDS.GetTarget(oldRes, EM_R("disabled"), true))
  3890.         ds.setItemProperty(item.id, EM_R("userDisabled"), EM_L("true"));
  3891.  
  3892.       // app enable all items. If it is incompatible it will be app disabled
  3893.       // later on.
  3894.       ds.setItemProperty(item.id, EM_R("appDisabled"), null);
  3895.  
  3896.       // if the item is already compatible don't attempt to migrate the
  3897.       // item's compatibility info
  3898.       var newRes = getResourceForID(itemsToCheck[i]);
  3899.       if (ds.isCompatible(ds, newRes))
  3900.         continue;
  3901.  
  3902.       var updatedMinVersion = null;
  3903.       var updatedMaxVersion = null;
  3904.       var targetApps = oldExtensionsDS.GetTargets(oldRes, EM_R("targetApplication"), true);
  3905.       while (targetApps.hasMoreElements()) {
  3906.         var targetApp = targetApps.getNext();
  3907.         if (targetApp instanceof Ci.nsIRDFResource) {
  3908.           try {
  3909.             var foundAppID = stringData(oldExtensionsDS.GetTarget(targetApp, EM_R("id"), true));
  3910.             // Different target application?  (Note:  v1.0 didn't support toolkit app ID)
  3911.             if (foundAppID != currAppID)
  3912.               continue;
  3913.  
  3914.             updatedMinVersion = stringData(oldExtensionsDS.GetTarget(targetApp, EM_R("minVersion"), true));
  3915.             updatedMaxVersion = stringData(oldExtensionsDS.GetTarget(targetApp, EM_R("maxVersion"), true));
  3916.  
  3917.             // Only set the target app info if the extension's target app info
  3918.             // in the version 1.0 extensions datasource makes it compatible
  3919.             if (versionChecker.compare(currAppVersion, updatedMinVersion) >= 0 &&
  3920.                 versionChecker.compare(currAppVersion, updatedMaxVersion) <= 0)
  3921.               ds.setTargetApplicationInfo(item.id, foundAppID, updatedMinVersion,
  3922.                                           updatedMaxVersion, null);
  3923.  
  3924.             break;
  3925.           }
  3926.           catch (e) {
  3927.           }
  3928.         }
  3929.       }
  3930.     }
  3931.   },
  3932.  
  3933.   /**
  3934.    * Write the Extensions List and the Startup Cache
  3935.    * @param   needsRestart
  3936.    *          true if the application needs to restart again, false otherwise.
  3937.    */
  3938.   _updateManifests: function(needsRestart) {
  3939.     // Write the Startup Cache (All Items, visible or not)
  3940.     StartupCache.write();
  3941.     // Write the Extensions Locations Manifest (Visible, enabled items)
  3942.     this._updateExtensionsManifest(needsRestart);
  3943.   },
  3944.  
  3945.   /**
  3946.    * Get a list of items that are currently "active" (turned on) of a specific
  3947.    * type
  3948.    * @param   type
  3949.    *          The nsIUpdateItem type to return a list of items of
  3950.    * @returns An array of active items of the specified type.
  3951.    */
  3952.   _getActiveItems: function(type) {
  3953.     var allItems = this.getItemList(type, { });
  3954.     var activeItems = [];
  3955.     var ds = this.datasource;
  3956.     for (var i = 0; i < allItems.length; ++i) {
  3957.       var item = allItems[i];
  3958.  
  3959.       var installLocation = this.getInstallLocation(item.id);
  3960.       // An entry with an invalid install location is not active.
  3961.       if (!installLocation)
  3962.         continue;
  3963.       // An item entry is valid only if it is not disabled, not about to
  3964.       // be disabled, and not about to be uninstalled.
  3965.       if (installLocation.name in StartupCache.entries &&
  3966.           item.id in StartupCache.entries[installLocation.name] &&
  3967.           StartupCache.entries[installLocation.name][item.id]) {
  3968.         var op = StartupCache.entries[installLocation.name][item.id].op;
  3969.         if (op == OP_NEEDS_INSTALL || op == OP_NEEDS_UPGRADE ||
  3970.             op == OP_NEEDS_UNINSTALL || op == OP_NEEDS_DISABLE)
  3971.           continue;
  3972.       }
  3973.       // Suppress items that have been disabled by the user or the app.
  3974.       if (ds.getItemProperty(item.id, "isDisabled") != "true")
  3975.         activeItems.push({ id: item.id, version: item.version,
  3976.                            location: installLocation });
  3977.     }
  3978.  
  3979.     return activeItems;
  3980.   },
  3981.  
  3982.   /**
  3983.    * Write the Extensions List
  3984.    * @param   needsRestart
  3985.    *          true if the application needs to restart again, false otherwise.
  3986.    */
  3987.   _updateExtensionsManifest: function(needsRestart) {
  3988.     // When an operation is performed that requires a component re-registration
  3989.     // (extension enabled/disabled, installed, uninstalled), we must write the
  3990.     // set of paths where extensions live so that the startup system can determine
  3991.     // where additional components, preferences, chrome manifests etc live.
  3992.     //
  3993.     // To do this we obtain a list of active extensions and themes and write
  3994.     // these to the extensions.ini file in the profile directory.
  3995.     var validExtensions = this._getActiveItems(Ci.nsIUpdateItem.TYPE_ANY -
  3996.                                                Ci.nsIUpdateItem.TYPE_THEME);
  3997.     var validThemes     = this._getActiveItems(Ci.nsIUpdateItem.TYPE_THEME);
  3998.  
  3999.     var extensionsLocationsFile = getFile(KEY_PROFILEDIR, [FILE_EXTENSION_MANIFEST]);
  4000.     var fos = openSafeFileOutputStream(extensionsLocationsFile);
  4001.  
  4002.     var enabledItems = [];
  4003.     var extensionSectionHeader = "[ExtensionDirs]\r\n";
  4004.     fos.write(extensionSectionHeader, extensionSectionHeader.length);
  4005.     for (var i = 0; i < validExtensions.length; ++i) {
  4006.       var e = validExtensions[i];
  4007.       var itemLocation = e.location.getItemLocation(e.id).QueryInterface(Ci.nsILocalFile);
  4008.       var descriptor = getAbsoluteDescriptor(itemLocation);
  4009.       var line = "Extension" + i + "=" + descriptor + "\r\n";
  4010.       fos.write(line, line.length);
  4011.       enabledItems.push(e.id + ":" + e.version);
  4012.     }
  4013.  
  4014.     var themeSectionHeader = "[ThemeDirs]\r\n";
  4015.     fos.write(themeSectionHeader, themeSectionHeader.length);
  4016.     for (i = 0; i < validThemes.length; ++i) {
  4017.       var e = validThemes[i];
  4018.       var itemLocation = e.location.getItemLocation(e.id).QueryInterface(Ci.nsILocalFile);
  4019.       var descriptor = getAbsoluteDescriptor(itemLocation);
  4020.       var line = "Extension" + i + "=" + descriptor + "\r\n";
  4021.       fos.write(line, line.length);
  4022.       enabledItems.push(e.id + ":" + e.version);
  4023.     }
  4024.  
  4025.     closeSafeFileOutputStream(fos);
  4026.  
  4027.     // Cache the enabled list for annotating the crash report subsequently
  4028.     gPref.setCharPref(PREF_EM_ENABLED_ITEMS, enabledItems.join(","));
  4029.  
  4030.     // Now refresh the compatibility manifest.
  4031.     this._extensionListChanged = needsRestart;
  4032.   },
  4033.  
  4034.   /**
  4035.    * Say whether or not the Extension List has changed (and thus whether or not
  4036.    * the system will have to restart the next time it is started).
  4037.    * @param   val
  4038.    *          true if the Extension List has changed, false otherwise.
  4039.    * @returns |val|
  4040.    */
  4041.   set _extensionListChanged(val) {
  4042.     // When an extension has an operation perform on it (e.g. install, upgrade,
  4043.     // disable, etc.) we are responsible for creating the .autoreg file and
  4044.     // nsAppRunner is responsible for removing it on restart. At some point it
  4045.     // may make sense to be able to cancel a registration but for now we only
  4046.     // create the file.
  4047.     try {
  4048.       var autoregFile = getFile(KEY_PROFILEDIR, [FILE_AUTOREG]);
  4049.       if (val && !autoregFile.exists())
  4050.         autoregFile.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  4051.     }
  4052.     catch (e) {
  4053.     }
  4054.     return val;
  4055.   },
  4056.  
  4057.   /**
  4058.    * Gathers data about an item specified by the supplied Install Manifest
  4059.    * and determines whether or not it can be installed as-is. It makes this
  4060.    * determination by validating the item's GUID, Version, and determining
  4061.    * if it is compatible with this application.
  4062.    * @param   installManifest
  4063.    *          A nsIRDFDataSource representing the Install Manifest of the
  4064.    *          item to be installed.
  4065.    * @return  A JS Object with the following properties:
  4066.    *          "id"       The GUID of the Item being installed.
  4067.    *          "version"  The Version string of the Item being installed.
  4068.    *          "name"     The Name of the Item being installed.
  4069.    *          "type"     The nsIUpdateItem type of the Item being installed.
  4070.    *          "targetApps" An array of TargetApplication Info Objects
  4071.    *                     with "id", "minVersion" and "maxVersion" properties,
  4072.    *                     representing applications targeted by this item.
  4073.    *          "error"    The result code:
  4074.    *                     INSTALLERROR_SUCCESS
  4075.    *                       no error, item can be installed
  4076.    *                     INSTALLERROR_INVALID_GUID
  4077.    *                       error, GUID is not well-formed
  4078.    *                     INSTALLERROR_INVALID_VERSION
  4079.    *                       error, Version is not well-formed
  4080.    *                     INSTALLERROR_INCOMPATIBLE_VERSION
  4081.    *                       error, item is not compatible with this version
  4082.    *                       of the application.
  4083.    *                     INSTALLERROR_INCOMPATIBLE_PLATFORM
  4084.    *                       error, item is not compatible with the operating
  4085.    *                       system or ABI the application was built for.
  4086.    *                     INSTALLERROR_INSECURE_UPDATE
  4087.    *                       error, item has no secure method of providing updates
  4088.    *                     INSTALLERROR_BLOCKLISTED
  4089.    *                       error, item is blocklisted
  4090.    */
  4091.   _getInstallData: function(installManifest) {
  4092.     var installData = { id          : "",
  4093.                         version     : "",
  4094.                         name        : "",
  4095.                         type        : 0,
  4096.                         error       : INSTALLERROR_SUCCESS,
  4097.                         targetApps  : [],
  4098.                         updateURL   : "",
  4099.                         updateKey   : "",
  4100.                         currentApp  : null };
  4101.  
  4102.     // Fetch properties from the Install Manifest
  4103.     installData.id       = getManifestProperty(installManifest, "id");
  4104.     installData.version  = getManifestProperty(installManifest, "version");
  4105.     installData.name     = getManifestProperty(installManifest, "name");
  4106.     installData.type     = getAddonTypeFromInstallManifest(installManifest);
  4107.     installData.updateURL= getManifestProperty(installManifest, "updateURL");
  4108.     installData.updateKey= getManifestProperty(installManifest, "updateKey");
  4109.  
  4110.     /**
  4111.      * Reads a property off a Target Application resource
  4112.      * @param   resource
  4113.      *          The RDF Resource for a Target Application
  4114.      * @param   property
  4115.      *          The property (less EM_NS) to read
  4116.      * @returns The string literal value of the property.
  4117.      */
  4118.     function readTAProperty(resource, property) {
  4119.       return stringData(installManifest.GetTarget(resource, EM_R(property), true));
  4120.     }
  4121.  
  4122.     var targetApps = installManifest.GetTargets(gInstallManifestRoot,
  4123.                                                 EM_R("targetApplication"),
  4124.                                                 true);
  4125.     while (targetApps.hasMoreElements()) {
  4126.       var targetApp = targetApps.getNext();
  4127.       if (targetApp instanceof Ci.nsIRDFResource) {
  4128.         try {
  4129.           var data = { id        : readTAProperty(targetApp, "id"),
  4130.                        minVersion: readTAProperty(targetApp, "minVersion"),
  4131.                        maxVersion: readTAProperty(targetApp, "maxVersion") };
  4132.           installData.targetApps.push(data);
  4133.           if ((data.id == gApp.ID) ||
  4134.               (data.id == TOOLKIT_ID) && !installData.currentApp)
  4135.             installData.currentApp = data;
  4136.         }
  4137.         catch (e) {
  4138.           continue;
  4139.         }
  4140.       }
  4141.     }
  4142.  
  4143.     // If the item specifies one or more target platforms, make sure our OS/ABI
  4144.     // combination is in the list - otherwise, refuse to install the item.
  4145.     var targetPlatforms = null;
  4146.     try {
  4147.       targetPlatforms = installManifest.GetTargets(gInstallManifestRoot,
  4148.                                                    EM_R("targetPlatform"),
  4149.                                                    true);
  4150.     } catch(e) {
  4151.       // No targetPlatform nodes, continue.
  4152.     }
  4153.     if (targetPlatforms != null && targetPlatforms.hasMoreElements()) {
  4154.       var foundMatchingOS = false;
  4155.       var foundMatchingOSAndABI = false;
  4156.       var requireABICompatibility = false;
  4157.       while (targetPlatforms.hasMoreElements()) {
  4158.         var targetPlatform = stringData(targetPlatforms.getNext());
  4159.         var os = targetPlatform.split("_")[0];
  4160.         var index = targetPlatform.indexOf("_");
  4161.         var abi = index != -1 ? targetPlatform.substr(index + 1) : null;
  4162.         if (os == gOSTarget) {
  4163.           foundMatchingOS = true;
  4164.           // The presence of any ABI part after our OS means ABI is important.
  4165.           if (abi != null) {
  4166.             requireABICompatibility = true;
  4167.             // If we don't know our ABI, we can't be compatible
  4168.             if (abi == gXPCOMABI && abi != UNKNOWN_XPCOM_ABI) {
  4169.               foundMatchingOSAndABI = true;
  4170.               break;
  4171.             }
  4172.           }
  4173.         }
  4174.       }
  4175.       if (!foundMatchingOS || (requireABICompatibility && !foundMatchingOSAndABI)) {
  4176.         installData.error = INSTALLERROR_INCOMPATIBLE_PLATFORM;
  4177.         return installData;
  4178.       }
  4179.     }
  4180.  
  4181.     // Validate the Item ID
  4182.     if (!gIDTest.test(installData.id)) {
  4183.       installData.error = INSTALLERROR_INVALID_GUID;
  4184.       return installData;
  4185.     }
  4186.     
  4187.     // Check that the add-on provides a secure update method.
  4188.     if (gCheckUpdateSecurity &&
  4189.         installData.updateURL &&
  4190.         installData.updateURL.substring(0, 6) != "https:" &&
  4191.         !installData.updateKey) {
  4192.       installData.error = INSTALLERROR_INSECURE_UPDATE;
  4193.       return installData;
  4194.     }
  4195.       
  4196.     // Check that the target application range allows compatibility with the app
  4197.     if (gCheckCompatibility &&
  4198.         !this.datasource.isCompatible(installManifest, gInstallManifestRoot, undefined)) {
  4199.       installData.error = INSTALLERROR_INCOMPATIBLE_VERSION;
  4200.       return installData;
  4201.     }
  4202.     
  4203.     // Check if the item is blocklisted.
  4204.     if (!gBlocklist)
  4205.       gBlocklist = Cc["@mozilla.org/extensions/blocklist;1"].
  4206.                    getService(Ci.nsIBlocklistService);
  4207.     if (gBlocklist.isAddonBlocklisted(installData.id, installData.version,
  4208.                                       null, null))
  4209.       installData.error = INSTALLERROR_BLOCKLISTED;
  4210.  
  4211.     return installData;
  4212.   },
  4213.  
  4214.   /**
  4215.    * Installs an item from a XPI/JAR file.
  4216.    * This is the main entry point into the Install system from outside code
  4217.    * (e.g. XPInstall).
  4218.    * @param   aXPIFile
  4219.    *          The file to install from.
  4220.    * @param   aInstallLocationKey
  4221.    *          The name of the Install Location where this item should be
  4222.    *          installed.
  4223.    */
  4224.   installItemFromFile: function(xpiFile, installLocationKey) {
  4225.     this.installItemFromFileInternal(xpiFile, installLocationKey, null);
  4226.  
  4227.     // If there are no compatibility checks running and no downloads in
  4228.     // progress then the install operations are complete.
  4229.     if (this._compatibilityCheckCount == 0 && this._transactions.length == 0) {
  4230.       for (var i = 0; i < this._installListeners.length; ++i)
  4231.         this._installListeners[i].onInstallsCompleted();
  4232.     }
  4233.   },
  4234.  
  4235.   /**
  4236.    * Installs an item from a XPI/JAR file.
  4237.    * @param   aXPIFile
  4238.    *          The file to install from.
  4239.    * @param   aInstallLocationKey
  4240.    *          The name of the Install Location where this item should be
  4241.    *          installed.
  4242.    * @param   aInstallManifest
  4243.    *          An updated Install Manifest from the Version Update check.
  4244.    *          Can be null when invoked from callers other than the Version
  4245.    *          Update check.
  4246.    */
  4247.   installItemFromFileInternal: function(aXPIFile, aInstallLocationKey, aInstallManifest) {
  4248.     var em = this;
  4249.     /**
  4250.      * Gets the Install Location for an Item.
  4251.      * @param   itemID
  4252.      *          The GUID of the item to find an Install Location for.
  4253.      * @return  An object implementing nsIInstallLocation which represents the
  4254.      *          location where the specified item should be installed.
  4255.      *          This can be:
  4256.      *          1. an object that corresponds to the location key supplied to
  4257.      *             |installItemFromFileInternal|,
  4258.      *          2. the default install location (the App Profile Extensions Folder)
  4259.      *             if no location key was supplied, or the location key supplied
  4260.      *             was not in the set of registered locations
  4261.      *          3. null, if the location selected by 1 or 2 above does not support
  4262.      *             installs from XPI/JAR files, or that location is not writable
  4263.      *             with the current access privileges.
  4264.      */
  4265.     function getInstallLocation(itemID) {
  4266.       // Here I use "upgrade" to mean "install a different version of an item".
  4267.       var installLocation = em.getInstallLocation(itemID);
  4268.       if (!installLocation) {
  4269.         // This is not an "upgrade", since we don't have any location data for the
  4270.         // extension ID specified - that is, it's not in our database.
  4271.  
  4272.         // Caller supplied a key to a registered location, use that location
  4273.         // for the installation
  4274.         installLocation = InstallLocations.get(aInstallLocationKey);
  4275.         if (installLocation) {
  4276.           // If the specified location does not have a common metadata location
  4277.           // (e.g. extensions have no common root, or other location specified
  4278.           // by the location implementation) - e.g. for a Registry Key enumeration
  4279.           // location - we cannot install or upgrade using a XPI file, probably
  4280.           // because these application types will be handling upgrading themselves.
  4281.           // Just bail.
  4282.           if (!installLocation.location) {
  4283.             LOG("Install Location \"" + installLocation.name + "\" does not support " +
  4284.                 "installation of items from XPI/JAR files. You must manage " +
  4285.                 "installation and update of these items yourself.");
  4286.             installLocation = null;
  4287.           }
  4288.         }
  4289.         else {
  4290.           // In the absence of a preferred install location, just default to
  4291.           // the App-Profile
  4292.           installLocation = InstallLocations.get(KEY_APP_PROFILE);
  4293.         }
  4294.       }
  4295.       else {
  4296.         // This is an "upgrade", but not through the Update System, because the
  4297.         // Update code will not let an extension with an incompatible target
  4298.         // app version range through to this point. This is an "upgrade" in the
  4299.         // sense that the user found a different version of an installed extension
  4300.         // and installed it through the web interface, so we have metadata.
  4301.  
  4302.         // If the location is different, return the preferred location rather than
  4303.         // the location of the currently installed version, because we may be in
  4304.         // the situation where an item is being installed into the global app
  4305.         // dir when there's a version in the profile dir.
  4306.         if (installLocation.name != aInstallLocationKey)
  4307.           installLocation = InstallLocations.get(aInstallLocationKey);
  4308.       }
  4309.       if (!installLocation.canAccess) {
  4310.         LOG("Install Location\"" + installLocation.name + "\" cannot be written " +
  4311.             "to with your access privileges. Installation will not proceed.");
  4312.         installLocation = null;
  4313.       }
  4314.       return installLocation;
  4315.     }
  4316.  
  4317.     /**
  4318.      * Stages a XPI file in the default item location specified by other
  4319.      * applications when they registered with XulRunner if the item's
  4320.      * install manifest specified compatibility with them.
  4321.      */
  4322.     function stageXPIForOtherApps(xpiFile, installData) {
  4323.       for (var i = 0; i < installData.targetApps.length; ++i) {
  4324.         var targetApp = installData.targetApps[i];
  4325.         if (targetApp.id != gApp.ID && targetApp.id != TOOLKIT_ID) {
  4326.         /* XXXben uncomment when this works!
  4327.           var settingsThingy = Cc[].
  4328.                                getService(Ci.nsIXULRunnerSettingsThingy);
  4329.           try {
  4330.             var appPrefix = "SOFTWARE\\Mozilla\\XULRunner\\Applications\\";
  4331.             var branch = settingsThingy.getBranch(appPrefix + targetApp.id);
  4332.             var path = branch.getProperty("ExtensionsLocation");
  4333.             var destination = Cc["@mozilla.org/file/local;1"].
  4334.                               createInstance(Ci.nsILocalFile);
  4335.             destination.initWithPath(path);
  4336.             xpiFile.copyTo(file, xpiFile.leafName);
  4337.           }
  4338.           catch (e) {
  4339.           }
  4340.          */
  4341.         }
  4342.       }
  4343.     }
  4344.  
  4345.     /**
  4346.      * Extracts and then starts the install for extensions / themes contained
  4347.      * within a xpi.
  4348.      */
  4349.     function installMultiXPI(xpiFile, installData) {
  4350.       var fileURL = getURIFromFile(xpiFile).QueryInterface(Ci.nsIURL);
  4351.       if (fileURL.fileExtension.toLowerCase() != "xpi") {
  4352.         LOG("Invalid File Extension: Item: \"" + fileURL.fileName + "\" has an " +
  4353.             "invalid file extension. Only xpi file extensions are allowed for " +
  4354.             "multiple item packages.");
  4355.         var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  4356.         showMessage("invalidFileExtTitle", [],
  4357.                     "invalidFileExtMessage", [installData.name,
  4358.                     fileURL.fileExtension,
  4359.                     bundle.GetStringFromName("type-" + installData.type)]);
  4360.         return;
  4361.       }
  4362.  
  4363.       try {
  4364.         var zipReader = getZipReaderForFile(xpiFile);
  4365.       }
  4366.       catch (e) {
  4367.         LOG("installMultiXPI: failed to open xpi file: " + xpiFile.path);
  4368.         throw e;
  4369.       }
  4370.  
  4371.       var searchForEntries = ["*.xpi", "*.jar"];
  4372.       var files = [];
  4373.       for (var i = 0; i < searchForEntries.length; ++i) {
  4374.         var entries = zipReader.findEntries(searchForEntries[i]);
  4375.         while (entries.hasMore()) {
  4376.           var entryName = entries.getNext();
  4377.           var target = getFile(KEY_TEMPDIR, [entryName]);
  4378.           try {
  4379.             target.createUnique(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  4380.           }
  4381.           catch (e) {
  4382.             LOG("installMultiXPI: failed to create target file for extraction " +
  4383.                 " file = " + target.path + ", exception = " + e + "\n");
  4384.           }
  4385.           zipReader.extract(entryName, target);
  4386.           files.push(target);
  4387.         }
  4388.       }
  4389.       zipReader.close();
  4390.  
  4391.       if (files.length == 0) {
  4392.         LOG("Multiple Item Package: Item: \"" + fileURL.fileName + "\" does " +
  4393.             "not contain a valid package to install.");
  4394.         var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  4395.         showMessage("missingPackageFilesTitle",
  4396.                     [bundle.GetStringFromName("type-" + installData.type)],
  4397.                     "missingPackageFilesMessage", [installData.name,
  4398.                     bundle.GetStringFromName("type-" + installData.type)]);
  4399.         return;
  4400.       }
  4401.  
  4402.       for (i = 0; i < files.length; ++i) {
  4403.         em.installItemFromFileInternal(files[i], aInstallLocationKey, null);
  4404.         files[i].remove(false);
  4405.       }
  4406.     }
  4407.  
  4408.     /**
  4409.      * An observer for the Extension Update System.
  4410.      * @constructor
  4411.      */
  4412.     function IncompatibleObserver() {}
  4413.     IncompatibleObserver.prototype = {
  4414.       _xpi: null,
  4415.       _installManifest: null,
  4416.  
  4417.       /**
  4418.        * Ask the Extension Update System if there are any version updates for
  4419.        * this item that will allow it to be compatible with this version of
  4420.        * the Application.
  4421.        * @param   item
  4422.        *          An nsIUpdateItem representing the item being installed.
  4423.        * @param   installManifest
  4424.        *          The Install Manifest datasource for the item.
  4425.        * @param   xpiFile
  4426.        *          The staged source XPI file that contains the item. Cleaned
  4427.        *          up by this process.
  4428.        * @param   installRDF
  4429.        *          The install.rdf file that was extracted from the xpi.
  4430.        */
  4431.       checkForUpdates: function(item, installManifest, xpiFile) {
  4432.         this._xpi             = xpiFile;
  4433.         this._installManifest = installManifest;
  4434.  
  4435.         for (var i = 0; i < em._installListeners.length; ++i)
  4436.           em._installListeners[i].onCompatibilityCheckStarted(item);
  4437.         em._compatibilityCheckCount++;
  4438.         em.update([item], 1, Ci.nsIExtensionManager.UPDATE_CHECK_COMPATIBILITY, this);
  4439.       },
  4440.  
  4441.       /**
  4442.        * See nsIExtensionManager.idl
  4443.        */
  4444.       onUpdateStarted: function() {
  4445.         LOG("Phone Home Listener: Update Started");
  4446.       },
  4447.  
  4448.       /**
  4449.        * See nsIExtensionManager.idl
  4450.        */
  4451.       onUpdateEnded: function() {
  4452.         LOG("Phone Home Listener: Update Ended");
  4453.       },
  4454.  
  4455.       /**
  4456.        * See nsIExtensionManager.idl
  4457.        */
  4458.       onAddonUpdateStarted: function(addon) {
  4459.         if (!addon)
  4460.           throw Cr.NS_ERROR_INVALID_ARG;
  4461.  
  4462.         LOG("Phone Home Listener: Update For " + addon.id + " started");
  4463.         em.datasource.addIncompatibleUpdateItem(addon.name, this._xpi.path,
  4464.                                                 addon.type, addon.version);
  4465.       },
  4466.  
  4467.       /**
  4468.        * See nsIExtensionManager.idl
  4469.        */
  4470.       onAddonUpdateEnded: function(addon, status) {
  4471.         if (!addon)
  4472.           throw Cr.NS_ERROR_INVALID_ARG;
  4473.  
  4474.         LOG("Phone Home Listener: Update For " + addon.id + " ended, status = " + status);
  4475.         em.datasource.removeDownload(this._xpi.path);
  4476.         LOG("Version Check Phone Home Completed");
  4477.  
  4478.         for (var i = 0; i < em._installListeners.length; ++i)
  4479.           em._installListeners[i].onCompatibilityCheckEnded(addon, status);
  4480.  
  4481.         // Only compatibility updates (e.g. STATUS_VERSIONINFO) are currently
  4482.         // supported
  4483.         if (status == Ci.nsIAddonUpdateCheckListener.STATUS_VERSIONINFO) {
  4484.           em.datasource.setTargetApplicationInfo(addon.id,
  4485.                                                  addon.targetAppID,
  4486.                                                  addon.minAppVersion,
  4487.                                                  addon.maxAppVersion,
  4488.                                                  this._installManifest);
  4489.  
  4490.           // Try and install again, but use the updated compatibility DB.
  4491.           // This will send out an apropriate onInstallEnded notification for us.
  4492.           em.installItemFromFileInternal(this._xpi, aInstallLocationKey,
  4493.                                          this._installManifest);
  4494.  
  4495.           // Add the updated compatibility info to the datasource if done
  4496.           if (StartupCache.entries[aInstallLocationKey][addon.id].op == OP_NONE) {
  4497.             em.datasource.setTargetApplicationInfo(addon.id,
  4498.                                                    addon.targetAppID,
  4499.                                                    addon.minAppVersion,
  4500.                                                    addon.maxAppVersion,
  4501.                                                    null);
  4502.           }
  4503.           else { // needs a restart
  4504.             // Add updatedMinVersion and updatedMaxVersion so it can be used
  4505.             // to update the datasource during the installation or upgrade.
  4506.             em.datasource.setUpdatedTargetAppInfo(addon.id,
  4507.                                                   addon.targetAppID,
  4508.                                                   addon.minAppVersion,
  4509.                                                   addon.maxAppVersion,
  4510.                                                   null);
  4511.           }
  4512.         }
  4513.         else {
  4514.           em.datasource.removeDownload(this._xpi.path);
  4515.           showIncompatibleError(installData);
  4516.           LOG("Add-on " + addon.id + " is incompatible with " +
  4517.               BundleManager.appName + " " + gApp.version + ", Toolkit " +
  4518.               gApp.platformVersion + ". Remote compatibility check did not " +
  4519.               "resolve this.");
  4520.           
  4521.           for (var i = 0; i < em._installListeners.length; ++i)
  4522.             em._installListeners[i].onInstallEnded(addon, INSTALLERROR_INCOMPATIBLE_VERSION);
  4523.  
  4524.           // We are responsible for cleaning up this file!
  4525.           InstallLocations.get(aInstallLocationKey).removeFile(this._xpi);
  4526.         }
  4527.  
  4528.         em._compatibilityCheckCount--;
  4529.         // If there are no more compatibility checks running and no downloads in
  4530.         // progress then the install operations are complete.
  4531.         if (em._compatibilityCheckCount == 0 && em._transactions.length == 0) {
  4532.           for (var i = 0; i < em._installListeners.length; ++i)
  4533.             em._installListeners[i].onInstallsCompleted();
  4534.         }
  4535.       },
  4536.  
  4537.       QueryInterface: XPCOMUtils.generateQI([Ci.nsIAddonUpdateCheckListener])
  4538.     }
  4539.  
  4540.     var shouldPhoneHomeIfNecessary = false;
  4541.     if (!aInstallManifest) {
  4542.       // If we were not called with an Install Manifest, we were called from
  4543.       // some other path than the Phone Home system, so we do want to phone
  4544.       // home if the version is incompatible. As this is the first point in the
  4545.       // install process we must notify observers here.
  4546.  
  4547.       var addon = makeItem(getURIFromFile(aXPIFile).spec, "",
  4548.                            aInstallLocationKey, "", "", "",
  4549.                            getURIFromFile(aXPIFile).spec,
  4550.                            "", "", "", "", 0, gApp.id);
  4551.       for (var i = 0; i < this._installListeners.length; ++i)
  4552.         this._installListeners[i].onInstallStarted(addon);
  4553.  
  4554.       shouldPhoneHomeIfNecessary = true;
  4555.       var installManifest = null;
  4556.       var installManifestFile = extractRDFFileToTempDir(aXPIFile,
  4557.                                                         FILE_INSTALL_MANIFEST,
  4558.                                                         true);
  4559.       if (installManifestFile.exists()) {
  4560.         installManifest = getInstallManifest(installManifestFile);
  4561.         installManifestFile.remove(false);
  4562.       }
  4563.       if (!installManifest) {
  4564.         LOG("The Install Manifest supplied by this item is not well-formed. " +
  4565.             "Installation will not proceed.");
  4566.         for (var i = 0; i < this._installListeners.length; ++i)
  4567.           this._installListeners[i].onInstallEnded(addon, INSTALLERROR_INVALID_MANIFEST);
  4568.         return;
  4569.       }
  4570.     }
  4571.     else
  4572.       installManifest = aInstallManifest;
  4573.  
  4574.     var installData = this._getInstallData(installManifest);
  4575.     // Recreate the add-on item with the full detail from the install manifest
  4576.     addon = makeItem(installData.id, installData.version,
  4577.                      aInstallLocationKey,
  4578.                      installData.currentApp ? installData.currentApp.minVersion : "",
  4579.                      installData.currentApp ? installData.currentApp.maxVersion : "",
  4580.                      installData.name,
  4581.                      getURIFromFile(aXPIFile).spec,
  4582.                      "", /* XPI Update Hash */
  4583.                      "", /* Icon URL */
  4584.                      installData.updateURL || "",
  4585.                      installData.updateKey || "",
  4586.                      installData.type,
  4587.                      installData.currentApp ? installData.currentApp.id : "");
  4588.  
  4589.     switch (installData.error) {
  4590.     case INSTALLERROR_INCOMPATIBLE_VERSION:
  4591.       // Since the caller cleans up |aXPIFile|, and we're not yet sure whether or
  4592.       // not we need it (we may need it if a remote version bump that makes it
  4593.       // compatible is discovered by the call home) - so we must stage it for
  4594.       // later ourselves.
  4595.       if (shouldPhoneHomeIfNecessary && installData.currentApp) {
  4596.         var installLocation = getInstallLocation(installData.id, aInstallLocationKey);
  4597.         if (!installLocation)
  4598.           return;
  4599.         var stagedFile = installLocation.stageFile(aXPIFile, installData.id);
  4600.         (new IncompatibleObserver(this)).checkForUpdates(addon, installManifest,
  4601.                                                          stagedFile);
  4602.         // Return early to prevent deletion of the install manifest file.
  4603.         return;
  4604.       }
  4605.       else {
  4606.         // XXXben Look up XULRunnerSettingsThingy to see if there is a registered
  4607.         //        app that can handle this item, if so just stage and don't show
  4608.         //        this error!
  4609.         showIncompatibleError(installData);
  4610.         LOG("Add-on " + installData.id + " is incompatible with " +
  4611.             BundleManager.appName + " " + gApp.version + ", Toolkit " +
  4612.             gApp.platformVersion + ". Remote compatibility check was not performed.");
  4613.       }
  4614.       break;
  4615.     case INSTALLERROR_SUCCESS:
  4616.       // Installation of multiple extensions / themes contained within a single xpi.
  4617.       if (installData.type == Ci.nsIUpdateItem.TYPE_MULTI_XPI) {
  4618.         installMultiXPI(aXPIFile, installData);
  4619.         break;
  4620.       }
  4621.  
  4622.       // Stage the extension's XPI so it can be extracted at the next restart.
  4623.       var installLocation = getInstallLocation(installData.id, aInstallLocationKey);
  4624.       if (!installLocation) {
  4625.         // No cleanup of any of the staged XPI files should be required here,
  4626.         // because this should only ever fail on the first recurse through
  4627.         // this function, BEFORE staging takes place... technically speaking
  4628.         // a location could become readonly during the phone home process,
  4629.         // but that's an edge case I don't care about.
  4630.         for (var i = 0; i < this._installListeners.length; ++i)
  4631.           this._installListeners[i].onInstallEnded(addon, INSTALLERROR_RESTRICTED);
  4632.         return;
  4633.       }
  4634.  
  4635.       // Stage a copy of the XPI/JAR file for our own evil purposes...
  4636.       stagedFile = installLocation.stageFile(aXPIFile, installData.id);
  4637.  
  4638.       var restartRequired = this.installRequiresRestart(installData.id,
  4639.                                                         installData.type);
  4640.       // Determine which configuration function to use based on whether or not
  4641.       // there is data about this item in our datasource already - if there is
  4642.       // we want to upgrade, otherwise we install fresh.
  4643.       var ds = this.datasource;
  4644.       if (installData.id in ds.visibleItems && ds.visibleItems[installData.id]) {
  4645.         // We enter this function if any data corresponding to an existing GUID
  4646.         // is found, regardless of its Install Location. We need to check before
  4647.         // "upgrading" an item that Install Location of the new item is of equal
  4648.         // or higher priority than the old item, to make sure the datasource only
  4649.         // ever tracks metadata for active items.
  4650.         var oldInstallLocation = this.getInstallLocation(installData.id);
  4651.         if (oldInstallLocation.priority >= installLocation.priority) {
  4652.           this._upgradeItem(installManifest, installData.id, installLocation,
  4653.                             installData.type);
  4654.           if (!restartRequired) {
  4655.             this._finalizeUpgrade(installData.id, installLocation);
  4656.             this._finalizeInstall(installData.id, stagedFile);
  4657.           }
  4658.         }
  4659.       }
  4660.       else {
  4661.         this._configureForthcomingItem(installManifest, installData.id,
  4662.                                         installLocation, installData.type);
  4663.         if (!restartRequired) {
  4664.           this._finalizeInstall(installData.id, stagedFile);
  4665.           if (installData.type == Ci.nsIUpdateItem.TYPE_THEME) {
  4666.             var internalName = this.datasource.getItemProperty(installData.id, "internalName");
  4667.             if (gPref.getBoolPref(PREF_EM_DSS_ENABLED)) {
  4668.               gPref.setCharPref(PREF_GENERAL_SKINS_SELECTEDSKIN, internalName);
  4669.             }
  4670.             else {
  4671.               gPref.setBoolPref(PREF_DSS_SWITCHPENDING, true);
  4672.               gPref.setCharPref(PREF_DSS_SKIN_TO_SELECT, internalName);
  4673.             }
  4674.           }
  4675.         }
  4676.       }
  4677.       this._updateManifests(restartRequired);
  4678.       break;
  4679.     case INSTALLERROR_INVALID_GUID:
  4680.       LOG("Invalid GUID: Item has GUID: \"" + installData.id + "\"" +
  4681.           " which is not well-formed.");
  4682.       var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  4683.       showMessage("incompatibleTitle",
  4684.                   [bundle.GetStringFromName("type-" + installData.type)],
  4685.                   "invalidGUIDMessage", [installData.name, installData.id]);
  4686.       break;
  4687.     case INSTALLERROR_INVALID_VERSION:
  4688.       LOG("Invalid Version: Item: \"" + installData.id + "\" has version " +
  4689.           installData.version + " which is not well-formed.");
  4690.       var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  4691.       showMessage("incompatibleTitle",
  4692.                   [bundle.GetStringFromName("type-" + installData.type)],
  4693.                   "invalidVersionMessage", [installData.name, installData.version]);
  4694.       break;
  4695.     case INSTALLERROR_INCOMPATIBLE_PLATFORM:
  4696.       const osABI = gOSTarget + "_" + gXPCOMABI;
  4697.       LOG("Incompatible Platform: Item: \"" + installData.id + "\" is not " +
  4698.           "compatible with '" + osABI + "'.");
  4699.       var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  4700.       showMessage("incompatibleTitle",
  4701.                   [bundle.GetStringFromName("type-" + installData.type)],
  4702.                   "incompatiblePlatformMessage",
  4703.                   [installData.name, BundleManager.appName, osABI]);
  4704.       break;
  4705.     case INSTALLERROR_BLOCKLISTED:
  4706.       LOG("Blocklisted Item: Item: \"" + installData.id + "\" version " +
  4707.           installData.version + " was not installed.");
  4708.       showBlocklistMessage([installData], true);
  4709.       break;
  4710.     case INSTALLERROR_INSECURE_UPDATE:
  4711.       LOG("No secure updates: Item: \"" + installData.id + "\" version " + 
  4712.           installData.version + " was not installed.");
  4713.       var bundle = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  4714.       showMessage("incompatibleTitle", 
  4715.                   [bundle.GetStringFromName("type-" + installData.type)], 
  4716.                   "insecureUpdateMessage", [installData.name]);
  4717.       break;
  4718.     default:
  4719.       break;
  4720.     }
  4721.  
  4722.     // Check to see if this item supports other applications and in that case
  4723.     // stage the the XPI file in the location specified by those applications.
  4724.     stageXPIForOtherApps(aXPIFile, installData);
  4725.  
  4726.     // The install of this item is complete, notify observers
  4727.     for (var i = 0; i < this._installListeners.length; ++i)
  4728.       this._installListeners[i].onInstallEnded(addon, installData.error);
  4729.   },
  4730.  
  4731.   /**
  4732.    * Whether or not this type's installation/uninstallation requires
  4733.    * the application to be restarted.
  4734.    * @param   id
  4735.    *          The GUID of the item
  4736.    * @param   type
  4737.    *          The nsIUpdateItem type of the item
  4738.    * @returns true if installation of an item of this type requires a
  4739.    *          restart.
  4740.    */
  4741.   installRequiresRestart: function(id, type) {
  4742.     switch (type) {
  4743.     case Ci.nsIUpdateItem.TYPE_THEME:
  4744.       var internalName = this.datasource.getItemProperty(id, "internalName");
  4745.       var needsRestart = false;
  4746.       if (gPref.prefHasUserValue(PREF_DSS_SKIN_TO_SELECT))
  4747.         needsRestart = internalName == gPref.getCharPref(PREF_DSS_SKIN_TO_SELECT);
  4748.       if (!needsRestart &&
  4749.           gPref.prefHasUserValue(PREF_GENERAL_SKINS_SELECTEDSKIN))
  4750.         needsRestart = internalName == gPref.getCharPref(PREF_GENERAL_SKINS_SELECTEDSKIN);
  4751.       return needsRestart;
  4752.     }
  4753.     return ((type & Ci.nsIUpdateItem.TYPE_ADDON) > 0);
  4754.   },
  4755.  
  4756.   /**
  4757.    * Perform initial configuration on an item that has just or will be
  4758.    * installed. This inserts the item into the appropriate container in the
  4759.    * datasource, so that the application UI shows the item even if it will
  4760.    * not actually be installed until the next restart.
  4761.    * @param   installManifest
  4762.    *          The Install Manifest datasource that describes this item.
  4763.    * @param   id
  4764.    *          The GUID of this item.
  4765.    * @param   installLocation
  4766.    *          The Install Location where this item is installed.
  4767.    * @param   type
  4768.    *          The nsIUpdateItem type of this item.
  4769.    */
  4770.   _configureForthcomingItem: function(installManifest, id, installLocation, type) {
  4771.     var ds = this.datasource;
  4772.     ds.updateVisibleList(id, installLocation.name, false);
  4773.  
  4774.     var name = null;
  4775.     var localized = findClosestLocalizedResource(installManifest, gInstallManifestRoot);
  4776.     if (localized)
  4777.       name = installManifest.GetTarget(localized, EM_R("name"), true);
  4778.     else
  4779.       name = EM_L(getManifestProperty(installManifest, "name"));
  4780.  
  4781.     var props = { name            : name,
  4782.                   version         : EM_L(getManifestProperty(installManifest, "version")),
  4783.                   newVersion      : EM_L(getManifestProperty(installManifest, "version")),
  4784.                   installLocation : EM_L(installLocation.name),
  4785.                   type            : EM_I(type),
  4786.                   availableUpdateURL    : null,
  4787.                   availableUpdateHash   : null,
  4788.                   availableUpdateVersion: null,
  4789.                   availableUpdateInfo   : null };
  4790.     for (var p in props)
  4791.       ds.setItemProperty(id, EM_R(p), props[p]);
  4792.     ds.updateProperty(id, "availableUpdateURL");
  4793.  
  4794.     this._setOp(id, OP_NEEDS_INSTALL);
  4795.  
  4796.     // Insert it into the child list NOW rather than later because:
  4797.     // - extensions installed using the command line need to be a member
  4798.     //   of a container during the install phase for the code to be able
  4799.     //   to identify profile vs. global
  4800.     // - extensions installed through the UI should show some kind of
  4801.     //   feedback to indicate their presence is forthcoming (i.e. they
  4802.     //   will be available after a restart).
  4803.     ds.insertItemIntoContainer(id);
  4804.  
  4805.     this._notifyAction(id, EM_ITEM_INSTALLED);
  4806.   },
  4807.  
  4808.   /**
  4809.    * Perform configuration on an item that has just or will be upgraded.
  4810.    * @param   installManifest
  4811.    *          The Install Manifest datasource that describes this item.
  4812.    * @param   itemID
  4813.    *          The GUID of this item.
  4814.    * @param   installLocation
  4815.    *          The Install Location where this item is installed.
  4816.    * @param   type
  4817.    *          The nsIUpdateItem type of this item.
  4818.    */
  4819.   _upgradeItem: function (installManifest, id, installLocation, type) {
  4820.     // Don't change any props that would need to be reset if the install fails.
  4821.     // They will be reset as appropriate by the upgrade/install process.
  4822.     var ds = this.datasource;
  4823.     ds.updateVisibleList(id, installLocation.name, false);
  4824.     var props = { installLocation : EM_L(installLocation.name),
  4825.                   type            : EM_I(type),
  4826.                   newVersion      : EM_L(getManifestProperty(installManifest, "version")),
  4827.                   availableUpdateURL      : null,
  4828.                   availableUpdateHash     : null,
  4829.                   availableUpdateVersion  : null,
  4830.                   availableUpdateInfo     : null };
  4831.     for (var p in props)
  4832.       ds.setItemProperty(id, EM_R(p), props[p]);
  4833.     ds.updateProperty(id, "availableUpdateURL");
  4834.  
  4835.     this._setOp(id, OP_NEEDS_UPGRADE);
  4836.     this._notifyAction(id, EM_ITEM_UPGRADED);
  4837.   },
  4838.  
  4839.   /**
  4840.    * Completes an Extension's installation.
  4841.    * @param   id
  4842.    *          The GUID of the Extension to install.
  4843.    * @param   file
  4844.    *          The XPI/JAR file to install from. If this is null, we try to
  4845.    *          determine the stage file location from the ID.
  4846.    */
  4847.   _finalizeInstall: function(id, file) {
  4848.     var ds = this.datasource;
  4849.     var type = ds.getItemProperty(id, "type");
  4850.     if (id == 0 || id == -1) {
  4851.       ds.removeCorruptItem(id);
  4852.       return;
  4853.     }
  4854.     var installLocation = this.getInstallLocation(id);
  4855.     if (!installLocation) {
  4856.       // If the install location is null, that means we've reached the finalize
  4857.       // state without the item ever having metadata added for it, which implies
  4858.       // bogus data in the Startup Cache. Clear the entries and don't do anything
  4859.       // else.
  4860.       var entries = StartupCache.findEntries(id);
  4861.       for (var i = 0; i < entries.length; ++i) {
  4862.         var location = InstallLocations.get(entries[i].location);
  4863.         StartupCache.clearEntry(location, id);
  4864.         PendingOperations.clearItem(OP_NEEDS_INSTALL, id);
  4865.       }
  4866.       return;
  4867.     }
  4868.     var itemLocation = installLocation.getItemLocation(id);
  4869.  
  4870.     if (!file && "stageFile" in installLocation)
  4871.       file = installLocation.getStageFile(id);
  4872.  
  4873.     // If |file| is null or does not exist, the installer assumes the item is
  4874.     // a dropped-in directory.
  4875.     var installer = new Installer(this.datasource, id, installLocation, type);
  4876.     installer.installFromFile(file);
  4877.  
  4878.     // If the file was staged, we must clean it up ourselves, otherwise the
  4879.     // EM caller is responsible for doing so (e.g. XPInstall)
  4880.     if (file)
  4881.       installLocation.removeFile(file);
  4882.  
  4883.     // Clear the op flag from the Startup Cache and Pending Operations sets
  4884.     StartupCache.put(installLocation, id, OP_NONE, true);
  4885.     PendingOperations.clearItem(OP_NEEDS_INSTALL, id);
  4886.   },
  4887.  
  4888.   /**
  4889.    * Removes an item's metadata in preparation for an upgrade-install.
  4890.    * @param   id
  4891.    *          The GUID of the item to uninstall.
  4892.    * @param   installLocation
  4893.    *          The nsIInstallLocation of the item
  4894.    */
  4895.   _finalizeUpgrade: function(id, installLocation) {
  4896.     // Retrieve the item properties *BEFORE* we clean the resource!
  4897.     var ds = this.datasource;
  4898.  
  4899.     var stagedFile = null;
  4900.     if ("getStageFile" in installLocation)
  4901.       stagedFile = installLocation.getStageFile(id);
  4902.  
  4903.     if (stagedFile)
  4904.       var installRDF = extractRDFFileToTempDir(stagedFile, FILE_INSTALL_MANIFEST, true);
  4905.     else
  4906.       installRDF = installLocation.getItemFile(id, FILE_INSTALL_MANIFEST);
  4907.     if (installRDF.exists()) {
  4908.       var installManifest = getInstallManifest(installRDF);
  4909.       if (installManifest) {
  4910.         var type = getAddonTypeFromInstallManifest(installManifest);
  4911.         var userDisabled = ds.getItemProperty(id, "userDisabled") == "true";
  4912.  
  4913.         // Clean the item resource
  4914.         ds.removeItemMetadata(id);
  4915.         // Now set up the properties on the item to mimic an item in its
  4916.         // "initial state" for installation.
  4917.         this._configureForthcomingItem(installManifest, id, installLocation,
  4918.                                        type);
  4919.         if (userDisabled)
  4920.           ds.setItemProperty(id, EM_R("userDisabled"), EM_L("true"));
  4921.       }
  4922.       if (stagedFile)
  4923.         installRDF.remove(false);
  4924.     }
  4925.     // Clear the op flag from the Pending Operations set. Do NOT clear op flag in
  4926.     // the startup cache since this may have been reset to OP_NEEDS_INSTALL by
  4927.     // |_configureForthcomingItem|.
  4928.     PendingOperations.clearItem(OP_NEEDS_UPGRADE, id);
  4929.   },
  4930.  
  4931.   /**
  4932.    * Completes an item's uninstallation.
  4933.    * @param   id
  4934.    *          The GUID of the item to uninstall.
  4935.    */
  4936.   _finalizeUninstall: function(id) {
  4937.     var ds = this.datasource;
  4938.  
  4939.     var installLocation = this.getInstallLocation(id);
  4940.     if (!installLocation.itemIsManagedIndependently(id)) {
  4941.       try {
  4942.         // Having a callback that does nothing just causes the directory to be
  4943.         // removed.
  4944.         safeInstallOperation(id, installLocation,
  4945.                              { data: null, callback: function() { } });
  4946.       }
  4947.       catch (e) {
  4948.         ERROR("_finalizeUninstall: failed to remove directory for item: " + id +
  4949.               " at Install Location: " + installLocation.name + ", rolling back uninstall");
  4950.         var manifest = installLocation.getItemFile(id, "FILE_INSTALL_MANIFEST");
  4951.         // If there is no manifest then either the rollback failed, or there was
  4952.         // no manifest in the first place. Either way this item is now invalid
  4953.         // and we shouldn't try to re-install it.
  4954.         if (manifest.exists()) {
  4955.           // Removal of the files failed, reset the uninstalled flag and rewrite
  4956.           // the install manifests so this item's components are registered.
  4957.           // Clear the op flag from the Startup Cache
  4958.           StartupCache.put(installLocation, id, OP_NONE, true);
  4959.           var restartRequired = this.installRequiresRestart(id, ds.getItemProperty(id, "type"))
  4960.           this._updateManifests(restartRequired);
  4961.           return;
  4962.         }
  4963.       }
  4964.     }
  4965.     else if (installLocation.name == KEY_APP_PROFILE ||
  4966.              installLocation.name == KEY_APP_GLOBAL ||
  4967.              installLocation.name == KEY_APP_SYSTEM_USER) {
  4968.       // Check for a pointer file and remove it if it exists
  4969.       var pointerFile = installLocation.location.clone();
  4970.       pointerFile.append(id);
  4971.       if (pointerFile.exists() && !pointerFile.isDirectory())
  4972.         pointerFile.remove(false);
  4973.     }
  4974.  
  4975.     // Clean the item resource
  4976.     ds.removeItemMetadata(id);
  4977.  
  4978.     // Do this LAST since inferences are made about an item based on
  4979.     // what container it's in.
  4980.     ds.removeItemFromContainer(id);
  4981.  
  4982.     // Clear the op flag from the Startup Cache and the Pending Operations set.
  4983.     StartupCache.clearEntry(installLocation, id);
  4984.     PendingOperations.clearItem(OP_NEEDS_UNINSTALL, id);
  4985.   },
  4986.  
  4987.   /**
  4988.    * Uninstalls an item. If the uninstallation cannot be performed immediately
  4989.    * it is scheduled for the next restart.
  4990.    * @param   id
  4991.    *          The GUID of the item to uninstall.
  4992.    */
  4993.   uninstallItem: function(id) {
  4994.     var ds = this.datasource;
  4995.     ds.updateDownloadState(PREFIX_ITEM_URI + id, null);
  4996.     if (!ds.isDownloadItem(id)) {
  4997.       var opType = ds.getItemProperty(id, "opType");
  4998.       var installLocation = this.getInstallLocation(id);
  4999.       // Removes any staged xpis for this item.
  5000.       if (opType == OP_NEEDS_UPGRADE || opType == OP_NEEDS_INSTALL) {
  5001.         var stageFile = installLocation.getStageFile(id);
  5002.         if (stageFile)
  5003.           installLocation.removeFile(stageFile);
  5004.       }
  5005.       // Addons with an opType of OP_NEEDS_INSTALL only have a staged xpi file
  5006.       // and are removed immediately since the uninstall can't be canceled.
  5007.       if (opType == OP_NEEDS_INSTALL) {
  5008.         ds.removeItemMetadata(id);
  5009.         ds.removeItemFromContainer(id);
  5010.         ds.updateVisibleList(id, null, true);
  5011.         StartupCache.clearEntry(installLocation, id);
  5012.         this._updateManifests(false);
  5013.       }
  5014.       else {
  5015.         if (opType == OP_NEEDS_UPGRADE)
  5016.           ds.setItemProperty(id, "newVersion", null);
  5017.         this._setOp(id, OP_NEEDS_UNINSTALL);
  5018.         var type = ds.getItemProperty(id, "type");
  5019.         var restartRequired = this.installRequiresRestart(id, type);
  5020.         if (!restartRequired) {
  5021.           this._finalizeUninstall(id);
  5022.           this._updateManifests(restartRequired);
  5023.         }
  5024.       }
  5025.     }
  5026.     else {
  5027.       // Bad download entry - uri is url, e.g. "http://www.foo.com/test.xpi"
  5028.       // ... just remove it from the list.
  5029.       ds.removeCorruptDLItem(id);
  5030.     }
  5031.  
  5032.     this._notifyAction(id, EM_ITEM_UNINSTALLED);
  5033.   },
  5034.  
  5035.   /* See nsIExtensionManager.idl */
  5036.   cancelInstallItem: function(id) {
  5037.     var ds = this.datasource;
  5038.     var opType = ds.getItemProperty(id, "opType");
  5039.     if (opType != OP_NEEDS_UPGRADE && opType != OP_NEEDS_INSTALL)
  5040.       return;
  5041.  
  5042.     ds.updateDownloadState(PREFIX_ITEM_URI + id, null);
  5043.     var installLocation = this.getInstallLocation(id);
  5044.     // Removes any staged xpis for this item.
  5045.     var stageFile = installLocation.getStageFile(id);
  5046.     if (stageFile)
  5047.       installLocation.removeFile(stageFile);
  5048.     // Addons with an opType of OP_NEEDS_INSTALL only have a staged xpi file
  5049.     // and just need to be removed completely from the ds.
  5050.     if (opType == OP_NEEDS_INSTALL) {
  5051.       ds.removeItemMetadata(id);
  5052.       ds.removeItemFromContainer(id);
  5053.       ds.updateVisibleList(id, null, true);
  5054.       StartupCache.clearEntry(installLocation, id);
  5055.       this._updateManifests(false);
  5056.       this._notifyAction(id, EM_ITEM_CANCEL);
  5057.     }
  5058.     else {
  5059.       // Clear upgrade information and reset any request to enable/disable.
  5060.       ds.setItemProperty(id, EM_R("newVersion"), null);
  5061.       var appDisabled = ds.getItemProperty(id, "appDisabled");
  5062.       var userDisabled = ds.getItemProperty(id, "userDisabled");
  5063.       if (appDisabled == "true" || appDisabled == OP_NONE && userDisabled == OP_NONE) {
  5064.         this._setOp(id, OP_NONE);
  5065.         this._notifyAction(id, EM_ITEM_CANCEL);
  5066.       }
  5067.       else if (appDisabled == OP_NEEDS_DISABLE || userDisabled == OP_NEEDS_DISABLE) {
  5068.         this._setOp(id, OP_NEEDS_DISABLE);
  5069.         this._notifyAction(id, EM_ITEM_DISABLED);
  5070.       }
  5071.       else if (appDisabled == OP_NEEDS_ENABLE || userDisabled == OP_NEEDS_ENABLE) {
  5072.         this._setOp(id, OP_NEEDS_ENABLE);
  5073.         this._notifyAction(id, EM_ITEM_ENABLED);
  5074.       }
  5075.       else {
  5076.         this._setOp(id, OP_NONE);
  5077.         this._notifyAction(id, EM_ITEM_CANCEL);
  5078.       }
  5079.     }
  5080.   },
  5081.  
  5082.   /**
  5083.    * Cancels a pending uninstall of an item
  5084.    * @param   id
  5085.    *          The ID of the item.
  5086.    */
  5087.   cancelUninstallItem: function(id) {
  5088.     var ds = this.datasource;
  5089.     var appDisabled = ds.getItemProperty(id, "appDisabled");
  5090.     var userDisabled = ds.getItemProperty(id, "userDisabled");
  5091.     if (appDisabled == "true" || appDisabled == OP_NONE && userDisabled == OP_NONE) {
  5092.       this._setOp(id, OP_NONE);
  5093.       this._notifyAction(id, EM_ITEM_CANCEL);
  5094.     }
  5095.     else if (appDisabled == OP_NEEDS_DISABLE || userDisabled == OP_NEEDS_DISABLE) {
  5096.       this._setOp(id, OP_NEEDS_DISABLE);
  5097.       this._notifyAction(id, EM_ITEM_DISABLED);
  5098.     }
  5099.     else if (appDisabled == OP_NEEDS_ENABLE || userDisabled == OP_NEEDS_ENABLE) {
  5100.       this._setOp(id, OP_NEEDS_ENABLE);
  5101.       this._notifyAction(id, EM_ITEM_ENABLED);
  5102.     }
  5103.     else {
  5104.       this._setOp(id, OP_NONE);
  5105.       this._notifyAction(id, EM_ITEM_CANCEL);
  5106.     }
  5107.   },
  5108.  
  5109.   /**
  5110.    * Sets the pending operation for a visible item.
  5111.    * @param   id
  5112.    *          The GUID of the item
  5113.    * @param   op
  5114.    *          The name of the operation to be performed
  5115.    */
  5116.   _setOp: function(id, op) {
  5117.     var location = this.getInstallLocation(id);
  5118.     StartupCache.put(location, id, op, true);
  5119.     PendingOperations.addItem(op, { locationKey: location.name, id: id });
  5120.     var ds = this.datasource;
  5121.     if (op == OP_NEEDS_INSTALL || op == OP_NEEDS_UPGRADE)
  5122.       ds.updateDownloadState(PREFIX_ITEM_URI + id, "success");
  5123.  
  5124.     ds.updateProperty(id, "opType");
  5125.     ds.updateProperty(id, "updateable");
  5126.     ds.updateProperty(id, "satisfiesDependencies");
  5127.     var restartRequired = this.installRequiresRestart(id, ds.getItemProperty(id, "type"))
  5128.     this._updateDependentItemsForID(id);
  5129.     this._updateManifests(restartRequired);
  5130.   },
  5131.  
  5132.   /**
  5133.    * Note on appDisabled and userDisabled property arcs.
  5134.    * The appDisabled and userDisabled RDF property arcs are used to store
  5135.    * the pending operation for app disabling and user disabling for an item as
  5136.    * well as the user and app disabled status after the pending operation has
  5137.    * been completed upon restart. When the appDisabled value changes the value
  5138.    * of userDisabled is reset to prevent the state of widgets and status
  5139.    * messages from being in an incorrect state.
  5140.    */
  5141.  
  5142.   /**
  5143.    * Enables an item for the application (e.g. the item satisfies all
  5144.    * requirements like app compatibility for it to be enabled). The appDisabled
  5145.    * property arc will be removed if the item will be app disabled on next
  5146.    * restart to cancel the app disabled operation for the item otherwise the
  5147.    * property value will be set to OP_NEEDS_ENABLE. The item's pending
  5148.    * operations are then evaluated in order to set the operation to perform
  5149.    * and notify the observers if the operation has been changed.
  5150.    * See "Note on appDisabled and userDisabled property arcs" above.
  5151.    * @param   id
  5152.    *          The ID of the item to be enabled by the application.
  5153.    */
  5154.   _appEnableItem: function(id) {
  5155.     var ds = this.datasource;
  5156.     var appDisabled = ds.getItemProperty(id, "appDisabled");
  5157.     if (appDisabled == OP_NONE || appDisabled == OP_NEEDS_ENABLE)
  5158.       return;
  5159.  
  5160.     var opType = ds.getItemProperty(id, "opType");
  5161.     var userDisabled = ds.getItemProperty(id, "userDisabled");
  5162.     // reset user disabled if it has a pending operation to prevent the ui
  5163.     // state from getting confused as to an item's current state.
  5164.     if (userDisabled == OP_NEEDS_DISABLE)
  5165.       ds.setItemProperty(id, EM_R("userDisabled"), null);
  5166.     else if (userDisabled == OP_NEEDS_ENABLE)
  5167.       ds.setItemProperty(id, EM_R("userDisabled"), EM_L("true"));
  5168.  
  5169.     if (appDisabled == OP_NEEDS_DISABLE)
  5170.       ds.setItemProperty(id, EM_R("appDisabled"), null);
  5171.     else if (appDisabled == "true")
  5172.       ds.setItemProperty(id, EM_R("appDisabled"), EM_L(OP_NEEDS_ENABLE));
  5173.  
  5174.     // Don't set a new operation when there is a pending uninstall operation.
  5175.     if (opType == OP_NEEDS_UNINSTALL) {
  5176.       this._updateDependentItemsForID(id);
  5177.       return;
  5178.     }
  5179.  
  5180.     var operation, action;
  5181.     // if this item is already enabled or user disabled don't set a pending
  5182.     // operation - instead immediately enable it and reset the operation type
  5183.     // if needed.
  5184.     if (appDisabled == OP_NEEDS_DISABLE || appDisabled == OP_NONE ||
  5185.         userDisabled == "true") {
  5186.       if (opType != OP_NONE) {
  5187.         operation = OP_NONE;
  5188.         action = EM_ITEM_CANCEL;
  5189.       }
  5190.     }
  5191.     else {
  5192.       if (opType != OP_NEEDS_ENABLE) {
  5193.         operation = OP_NEEDS_ENABLE;
  5194.         action = EM_ITEM_ENABLED;
  5195.       }
  5196.     }
  5197.  
  5198.     if (action) {
  5199.       this._setOp(id, operation);
  5200.       this._notifyAction(id, action);
  5201.     }
  5202.     else {
  5203.       ds.updateProperty(id, "satisfiesDependencies");
  5204.       this._updateDependentItemsForID(id);
  5205.     }
  5206.   },
  5207.  
  5208.   /**
  5209.    * Disables an item for the application (e.g. the item doesn't satisfy all
  5210.    * requirements like app compatibility for it to be enabled). The appDisabled
  5211.    * property arc will be set to true if the item will be app enabled on next
  5212.    * restart to cancel the app enabled operation for the item otherwise the
  5213.    * property value will be set to OP_NEEDS_DISABLE. The item's pending
  5214.    * operations are then evaluated in order to set the operation to perform
  5215.    * and notify the observers if the operation has been changed.
  5216.    * See "Note on appDisabled and userDisabled property arcs" above.
  5217.    * @param   id
  5218.    *          The ID of the item to be disabled by the application.
  5219.    */
  5220.   _appDisableItem: function(id) {
  5221.     var ds = this.datasource;
  5222.     var appDisabled = ds.getItemProperty(id, "appDisabled");
  5223.     if (appDisabled == "true" || appDisabled == OP_NEEDS_DISABLE)
  5224.       return;
  5225.  
  5226.     var opType = ds.getItemProperty(id, "opType");
  5227.     var userDisabled = ds.getItemProperty(id, "userDisabled");
  5228.  
  5229.     // reset user disabled if it has a pending operation to prevent the ui
  5230.     // state from getting confused as to an item's current state.
  5231.     if (userDisabled == OP_NEEDS_DISABLE)
  5232.       ds.setItemProperty(id, EM_R("userDisabled"), null);
  5233.     else if (userDisabled == OP_NEEDS_ENABLE)
  5234.       ds.setItemProperty(id, EM_R("userDisabled"), EM_L("true"));
  5235.  
  5236.     if (appDisabled == OP_NEEDS_ENABLE || userDisabled == OP_NEEDS_ENABLE ||
  5237.         ds.getItemProperty(id, "userDisabled") == "true")
  5238.       ds.setItemProperty(id, EM_R("appDisabled"), EM_L("true"));
  5239.     else if (appDisabled == OP_NONE)
  5240.       ds.setItemProperty(id, EM_R("appDisabled"), EM_L(OP_NEEDS_DISABLE));
  5241.  
  5242.     // Don't set a new operation when there is a pending uninstall operation.
  5243.     if (opType == OP_NEEDS_UNINSTALL) {
  5244.       this._updateDependentItemsForID(id);
  5245.       return;
  5246.     }
  5247.  
  5248.     var operation, action;
  5249.     // if this item is already disabled don't set a pending operation - instead
  5250.     // immediately disable it and reset the operation type if needed.
  5251.     if (appDisabled == OP_NEEDS_ENABLE || appDisabled == "true" ||
  5252.         userDisabled == OP_NEEDS_ENABLE || userDisabled == "true") {
  5253.       if (opType != OP_NONE) {
  5254.         operation = OP_NONE;
  5255.         action = EM_ITEM_CANCEL;
  5256.       }
  5257.     }
  5258.     else {
  5259.       if (opType != OP_NEEDS_DISABLE) {
  5260.         operation = OP_NEEDS_DISABLE;
  5261.         action = EM_ITEM_DISABLED;
  5262.       }
  5263.     }
  5264.  
  5265.     if (action) {
  5266.       this._setOp(id, operation);
  5267.       this._notifyAction(id, action);
  5268.     }
  5269.     else {
  5270.       ds.updateProperty(id, "satisfiesDependencies");
  5271.       this._updateDependentItemsForID(id);
  5272.     }
  5273.   },
  5274.  
  5275.   /**
  5276.    * Sets an item to be enabled by the user. If the item is already enabled this
  5277.    * clears the needs-enable operation for the next restart.
  5278.    * See "Note on appDisabled and userDisabled property arcs" above.
  5279.    * @param   id
  5280.    *          The ID of the item to be enabled by the user.
  5281.    */
  5282.   enableItem: function(id) {
  5283.     var ds = this.datasource;
  5284.     var opType = ds.getItemProperty(id, "opType");
  5285.     var appDisabled = ds.getItemProperty(id, "appDisabled");
  5286.     var userDisabled = ds.getItemProperty(id, "userDisabled");
  5287.  
  5288.     var operation, action;
  5289.     // if this item is already enabled don't set a pending operation - instead
  5290.     // immediately enable it and reset the operation type if needed.
  5291.     if (appDisabled == OP_NONE &&
  5292.         userDisabled == OP_NEEDS_DISABLE || userDisabled == OP_NONE) {
  5293.       if (userDisabled == OP_NEEDS_DISABLE)
  5294.         ds.setItemProperty(id, EM_R("userDisabled"), null);
  5295.       if (opType != OP_NONE) {
  5296.         operation = OP_NONE;
  5297.         action = EM_ITEM_CANCEL;
  5298.       }
  5299.     }
  5300.     else {
  5301.       if (userDisabled == "true")
  5302.         ds.setItemProperty(id, EM_R("userDisabled"), EM_L(OP_NEEDS_ENABLE));
  5303.       if (opType != OP_NEEDS_ENABLE) {
  5304.         operation = OP_NEEDS_ENABLE;
  5305.         action = EM_ITEM_ENABLED;
  5306.       }
  5307.     }
  5308.  
  5309.     if (action) {
  5310.       this._setOp(id, operation);
  5311.       this._notifyAction(id, action);
  5312.     }
  5313.     else {
  5314.       ds.updateProperty(id, "satisfiesDependencies");
  5315.       this._updateDependentItemsForID(id);
  5316.     }
  5317.   },
  5318.  
  5319.   /**
  5320.    * Sets an item to be disabled by the user. If the item is already disabled
  5321.    * this clears the needs-disable operation for the next restart.
  5322.    * See "Note on appDisabled and userDisabled property arcs" above.
  5323.    * @param   id
  5324.    *          The ID of the item to be disabled by the user.
  5325.    */
  5326.   disableItem: function(id) {
  5327.     var ds = this.datasource;
  5328.     var opType = ds.getItemProperty(id, "opType");
  5329.     var appDisabled = ds.getItemProperty(id, "appDisabled");
  5330.     var userDisabled = ds.getItemProperty(id, "userDisabled");
  5331.  
  5332.     var operation, action;
  5333.     // if this item is already disabled don't set a pending operation - instead
  5334.     // immediately disable it and reset the operation type if needed.
  5335.     if (userDisabled == OP_NEEDS_ENABLE || userDisabled == "true" ||
  5336.         appDisabled == OP_NEEDS_ENABLE) {
  5337.       if (userDisabled != "true")
  5338.         ds.setItemProperty(id, EM_R("userDisabled"), EM_L("true"));
  5339.       if (opType != OP_NONE) {
  5340.         operation = OP_NONE;
  5341.         action = EM_ITEM_CANCEL;
  5342.       }
  5343.     }
  5344.     else {
  5345.       if (userDisabled == OP_NONE)
  5346.         ds.setItemProperty(id, EM_R("userDisabled"), EM_L(OP_NEEDS_DISABLE));
  5347.       if (opType != OP_NEEDS_DISABLE) {
  5348.         operation = OP_NEEDS_DISABLE;
  5349.         action = EM_ITEM_DISABLED;
  5350.       }
  5351.     }
  5352.  
  5353.     if (action) {
  5354.       this._setOp(id, operation);
  5355.       this._notifyAction(id, action);
  5356.     }
  5357.     else {
  5358.       ds.updateProperty(id, "satisfiesDependencies");
  5359.       this._updateDependentItemsForID(id);
  5360.     }
  5361.   },
  5362.  
  5363.   /**
  5364.    * Determines whether an item should be disabled by the application.
  5365.    * @param   id
  5366.    *          The ID of the item to check
  5367.    */
  5368.   _isUsableItem: function(id) {
  5369.     var ds = this.datasource;
  5370.     /* If we're not compatibility checking or if the item is compatible
  5371.      * and if it isn't blocklisted and has all dependencies satisfied then
  5372.      * proceed to the security check */
  5373.     if ((!gCheckCompatibility || ds.getItemProperty(id, "compatible") == "true") &&
  5374.         ds.getItemProperty(id, "blocklisted") == "false" &&
  5375.         ds.getItemProperty(id, "satisfiesDependencies") == "true") {
  5376.  
  5377.       // appManaged items aren't updated so no need to check update security.
  5378.       if (ds.getItemProperty(id, "appManaged") == "true")
  5379.         return true;
  5380.  
  5381.       /* If we are not ignoring update security then check that the item has
  5382.        * a secure update mechanism */
  5383.       return (!gCheckUpdateSecurity ||
  5384.               ds.getItemProperty(id, "providesUpdatesSecurely") == "true");
  5385.     }
  5386.     return false;
  5387.   },
  5388.  
  5389.   /**
  5390.    * Sets an item's dependent items disabled state for the app based on whether
  5391.    * its dependencies are met and the item is compatible.
  5392.    * @param   id
  5393.    *          The ID of the item whose dependent items will be checked
  5394.    */
  5395.   _updateDependentItemsForID: function(id) {
  5396.     var ds = this.datasource;
  5397.     var dependentItems = this.getDependentItemListForID(id, true, { });
  5398.     for (var i = 0; i < dependentItems.length; ++i) {
  5399.       var dependentID = dependentItems[i].id;
  5400.       ds.updateProperty(dependentID, "satisfiesDependencies");
  5401.       if (this._isUsableItem(dependentID))
  5402.         this._appEnableItem(dependentID);
  5403.       else
  5404.         this._appDisableItem(dependentID);
  5405.     }
  5406.   },
  5407.  
  5408.   /**
  5409.    * Notify observers of a change to an item that has been requested by the
  5410.    * user.
  5411.    */
  5412.   _notifyAction: function(id, reason) {
  5413.     gOS.notifyObservers(this.datasource.getItemForID(id),
  5414.                         EM_ACTION_REQUESTED_TOPIC, reason);
  5415.   },
  5416.  
  5417.   /**
  5418.    * See nsIExtensionManager.idl
  5419.    */
  5420.   update: function(items, itemCount, updateCheckType, listener) {
  5421.     for (i = 0; i < itemCount; ++i) {
  5422.       var currItem = items[i];
  5423.       if (!currItem)
  5424.         throw Cr.NS_ERROR_ILLEGAL_VALUE;
  5425.     }
  5426.  
  5427.     if (items.length == 0)
  5428.       items = this.getItemList(Ci.nsIUpdateItem.TYPE_ANY, { });
  5429.  
  5430.     var updater = new ExtensionItemUpdater(this);
  5431.     updater.checkForUpdates(items, items.length, updateCheckType, listener);
  5432.   },
  5433.  
  5434.  
  5435.   /**
  5436.    * Checks for changes to the blocklist using the local blocklist file,
  5437.    * application disables / enables items that have been added / removed from
  5438.    * the blocklist, and if there are additions to the blocklist this will
  5439.    * inform the user by displaying a list of the items added.
  5440.    *
  5441.    * XXXrstrong - this method is not terribly useful and was added so we can
  5442.    * trigger this check from the additional timer used by blocklisting.
  5443.    */
  5444.   checkForBlocklistChanges: function() {
  5445.     var ds = this.datasource;
  5446.     var items = this.getItemList(Ci.nsIUpdateItem.TYPE_ANY, { });
  5447.     for (var i = 0; i < items.length; ++i) {
  5448.       var id = items[i].id;
  5449.       ds.updateProperty(id, "blocklisted");
  5450.       if (this._isUsableItem(id))
  5451.         this._appEnableItem(id);
  5452.     }
  5453.  
  5454.     items = ds.getBlocklistedItemList(null, null, Ci.nsIUpdateItem.TYPE_ANY,
  5455.                                       false);
  5456.     for (i = 0; i < items.length; ++i)
  5457.       this._appDisableItem(items[i].id);
  5458.  
  5459.     // show the blocklist notification window if there are new blocklist items.
  5460.     if (items.length > 0)
  5461.       showBlocklistMessage(items, false);
  5462.   },
  5463.  
  5464.   /**
  5465.    * @returns An enumeration of all registered Install Locations.
  5466.    */
  5467.   get installLocations () {
  5468.     return InstallLocations.enumeration;
  5469.   },
  5470.  
  5471.   /**
  5472.    * Gets the Install Location where a visible Item is stored.
  5473.    * @param   id
  5474.    *          The GUID of the item to locate an Install Location for.
  5475.    * @returns The Install Location object where the item is stored.
  5476.    */
  5477.   getInstallLocation: function(id) {
  5478.     var key = this.datasource.visibleItems[id];
  5479.     return key ? InstallLocations.get(this.datasource.visibleItems[id]) : null;
  5480.   },
  5481.  
  5482.   /**
  5483.    * Gets a nsIUpdateItem for the item with the specified id.
  5484.    * @param   id
  5485.    *          The GUID of the item to construct a nsIUpdateItem for.
  5486.    * @returns The nsIUpdateItem representing the item.
  5487.    */
  5488.   getItemForID: function(id) {
  5489.     return this.datasource.getItemForID(id);
  5490.   },
  5491.  
  5492.   /**
  5493.    * Retrieves a list of installed nsIUpdateItems of items that are dependent
  5494.    * on another item.
  5495.    * @param   id
  5496.    *          The ID of the item that other items depend on.
  5497.    * @param   includeDisabled
  5498.    *          Whether to include disabled items in the set returned.
  5499.    * @param   countRef
  5500.    *          The XPCJS reference to the number of items returned.
  5501.    * @returns An array of installed nsIUpdateItems that depend on the item
  5502.    *          specified by the id parameter.
  5503.    */
  5504.   getDependentItemListForID: function(id, includeDisabled, countRef) {
  5505.     return this.datasource.getDependentItemListForID(id, includeDisabled, countRef);
  5506.   },
  5507.  
  5508.   /**
  5509.    * Retrieves a list of nsIUpdateItems of items matching the specified type.
  5510.    * @param   type
  5511.    *          The type of item to return.
  5512.    * @param   countRef
  5513.    *          The XPCJS reference to the number of items returned.
  5514.    * @returns An array of nsIUpdateItems matching the id/type filter.
  5515.    */
  5516.   getItemList: function(type, countRef) {
  5517.     return this.datasource.getItemList(type, countRef);
  5518.   },
  5519.  
  5520.   /* See nsIExtensionManager.idl */
  5521.   getIncompatibleItemList: function(id, appVersion, platformVersion, type, includeDisabled,
  5522.                                     countRef) {
  5523.     var items = this.datasource.getIncompatibleItemList(id, appVersion ? appVersion : undefined,
  5524.                                                         platformVersion ? platformVersion : undefined,
  5525.                                                         type, includeDisabled);
  5526.     countRef.value = items.length;
  5527.     return items;
  5528.   },
  5529.  
  5530.   /**
  5531.    * Move an Item to the index of another item in its container.
  5532.    * @param   movingID
  5533.    *          The ID of the item to be moved.
  5534.    * @param   destinationID
  5535.    *          The ID of an item to move another item to.
  5536.    */
  5537.   moveToIndexOf: function(movingID, destinationID) {
  5538.     this.datasource.moveToIndexOf(movingID, destinationID);
  5539.   },
  5540.  
  5541.   /**
  5542.    * Sorts addons of the specified type by the specified property starting from
  5543.    * the top of their container. If the addons are already sorted then no action
  5544.    * is performed.
  5545.    * @param   type
  5546.    *          The nsIUpdateItem type of the items to sort.
  5547.    * @param   propertyName
  5548.    *          The RDF property name used for sorting.
  5549.    * @param   isAscending
  5550.    *          true to sort ascending and false to sort descending
  5551.    */
  5552.   sortTypeByProperty: function(type, propertyName, isAscending) {
  5553.     this.datasource.sortTypeByProperty(type, propertyName, isAscending);
  5554.   },
  5555.  
  5556.   /////////////////////////////////////////////////////////////////////////////
  5557.   // Downloads
  5558.   _transactions: [],
  5559.   _downloadCount: 0,
  5560.   _compatibilityCheckCount: 0,
  5561.  
  5562.   /**
  5563.    * Ask the user if they really want to quit the application, since this will
  5564.    * cancel one or more Extension/Theme downloads.
  5565.    * @param   subject
  5566.    *          A nsISupportsPRBool which this function sets to false if the user
  5567.    *          wishes to cancel all active downloads and quit the application,
  5568.    *          false otherwise.
  5569.    */
  5570.   _confirmCancelDownloadsOnQuit: function(subject) {
  5571.     // If user has already dismissed quit request, then do nothing
  5572.     if ((subject instanceof Ci.nsISupportsPRBool) && subject.data)
  5573.       return;
  5574.  
  5575.     if (this._downloadCount > 0) {
  5576.       // The observers will be notified again after this so set the download
  5577.       // count to 0 to prevent this dialog from being displayed again.
  5578.       this._downloadCount = 0;
  5579.       var result;
  5580. //@line 5559 "e:\builds\tinderbox\XR-Trunk\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  5581.       result = this._confirmCancelDownloads(this._downloadCount,
  5582.                                             "quitCancelDownloadsAlertTitle",
  5583.                                             "quitCancelDownloadsAlertMsgMultiple",
  5584.                                             "quitCancelDownloadsAlertMsg",
  5585.                                             "dontQuitButtonWin");
  5586. //@line 5571 "e:\builds\tinderbox\XR-Trunk\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  5587.       if (subject instanceof Ci.nsISupportsPRBool)
  5588.         subject.data = result;
  5589.     }
  5590.   },
  5591.  
  5592.   /**
  5593.    * Ask the user if they really want to go offline, since this will cancel
  5594.    * one or more Extension/Theme downloads.
  5595.    * @param   subject
  5596.    *          A nsISupportsPRBool which this function sets to false if the user
  5597.    *          wishes to cancel all active downloads and go offline, false
  5598.    *          otherwise.
  5599.    */
  5600.   _confirmCancelDownloadsOnOffline: function(subject) {
  5601.     if (this._downloadCount > 0) {
  5602.       result = this._confirmCancelDownloads(this._downloadCount,
  5603.                                             "offlineCancelDownloadsAlertTitle",
  5604.                                             "offlineCancelDownloadsAlertMsgMultiple",
  5605.                                             "offlineCancelDownloadsAlertMsg",
  5606.                                             "dontGoOfflineButton");
  5607.       if (subject instanceof Ci.nsISupportsPRBool)
  5608.         subject.data = result;
  5609.     }
  5610.   },
  5611.  
  5612.   /**
  5613.    * Ask the user whether or not they wish to cancel the Extension/Theme
  5614.    * downloads which are currently under way.
  5615.    * @param   count
  5616.    *          The number of active downloads.
  5617.    * @param   title
  5618.    *          The key of the title for the message box to be displayed
  5619.    * @param   cancelMessageMultiple
  5620.    *          The key of the message to be displayed in the message box
  5621.    *          when there are > 1 active downloads.
  5622.    * @param   cancelMessageSingle
  5623.    *          The key of the message to be displayed in the message box
  5624.    *          when there is just one active download.
  5625.    * @param   dontCancelButton
  5626.    *          The key of the label to be displayed on the "Don't Cancel
  5627.    *          Downloads" button.
  5628.    */
  5629.   _confirmCancelDownloads: function(count, title, cancelMessageMultiple,
  5630.                                     cancelMessageSingle, dontCancelButton) {
  5631.     var bundle = BundleManager.getBundle(URI_DOWNLOADS_PROPERTIES);
  5632.     var title = bundle.GetStringFromName(title);
  5633.     var message, quitButton;
  5634.     if (count > 1) {
  5635.       message = bundle.formatStringFromName(cancelMessageMultiple, [count], 1);
  5636.       quitButton = bundle.formatStringFromName("cancelDownloadsOKTextMultiple", [count], 1);
  5637.     }
  5638.     else {
  5639.       message = bundle.GetStringFromName(cancelMessageSingle);
  5640.       quitButton = bundle.GetStringFromName("cancelDownloadsOKText");
  5641.     }
  5642.     var dontQuitButton = bundle.GetStringFromName(dontCancelButton);
  5643.  
  5644.     var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
  5645.              getService(Ci.nsIWindowMediator);
  5646.     var win = wm.getMostRecentWindow("Extension:Manager");
  5647.     const nsIPromptService = Ci.nsIPromptService;
  5648.     var ps = Cc["@mozilla.org/embedcomp/prompt-service;1"].
  5649.              getService(nsIPromptService);
  5650.     var flags = (nsIPromptService.BUTTON_TITLE_IS_STRING * nsIPromptService.BUTTON_POS_0) +
  5651.                 (nsIPromptService.BUTTON_TITLE_IS_STRING * nsIPromptService.BUTTON_POS_1);
  5652.     var rv = ps.confirmEx(win, title, message, flags, quitButton, dontQuitButton, null, null, { });
  5653.     return rv == 1;
  5654.   },
  5655.  
  5656.   /* See nsIExtensionManager.idl */
  5657.   addDownloads: function(items, itemCount, manager) {
  5658.     if (itemCount == 0)
  5659.       throw Cr.NS_ERROR_ILLEGAL_VALUE;
  5660.  
  5661.     for (i = 0; i < itemCount; ++i) {
  5662.       var currItem = items[i];
  5663.       if (!currItem)
  5664.         throw Cr.NS_ERROR_ILLEGAL_VALUE;
  5665.     }
  5666.  
  5667.     var ds = this.datasource;
  5668.     // Add observers only if they aren't already added for an active download
  5669.     if (this._downloadCount == 0) {
  5670.       gOS.addObserver(this, "offline-requested", false);
  5671.       gOS.addObserver(this, "quit-application-requested", false);
  5672.     }
  5673.     this._downloadCount += itemCount;
  5674.  
  5675.     var urls = [];
  5676.     var hashes = [];
  5677.     var txnID = Math.round(Math.random() * 100);
  5678.     var txn = new ItemDownloadTransaction(this, txnID);
  5679.     for (var i = 0; i < itemCount; ++i) {
  5680.       var currItem = items[i];
  5681.  
  5682.       txn.addDownload(currItem);
  5683.       urls.push(currItem.xpiURL);
  5684.       hashes.push(currItem.xpiHash ? currItem.xpiHash : null);
  5685.       // if this is an update remove the update metadata to prevent it from
  5686.       // being updated during an install.
  5687.       if (!manager) {
  5688.         var id = currItem.id
  5689.         ds.setItemProperty(id, EM_R("availableUpdateURL"), null);
  5690.         ds.setItemProperty(id, EM_R("availableUpdateHash"), null);
  5691.         ds.setItemProperty(id, EM_R("availableUpdateVersion"), null);
  5692.         ds.setItemProperty(id, EM_R("availableUpdateInfo"), null);
  5693.         ds.updateProperty(id, "availableUpdateURL");
  5694.         ds.updateProperty(id, "updateable");
  5695.       }
  5696.       var id = !manager ? PREFIX_ITEM_URI + currItem.id : currItem.xpiURL;
  5697.       ds.updateDownloadState(id, "waiting");
  5698.     }
  5699.     this._transactions.push(txn);
  5700.  
  5701.     if (manager) {
  5702.       // XPIManager initiated -- let it know we're ready
  5703.       manager.observe(txn, "xpinstall-progress", "open");
  5704.     }
  5705.     else {
  5706.       // Initiate an install from chrome
  5707.       var xpimgr = Cc["@mozilla.org/xpinstall/install-manager;1"].
  5708.                    createInstance(Ci.nsIXPInstallManager);
  5709.       xpimgr.initManagerWithHashes(urls, hashes, urls.length, txn);
  5710.     }
  5711.   },
  5712.  
  5713.   /**
  5714.    * Download Operation State has changed from one to another.
  5715.    *
  5716.    * The nsIXPIProgressDialog implementation in the download transaction object
  5717.    * forwards notifications through these methods which we then pass on to any
  5718.    * front end objects implementing nsIExtensionDownloadListener that
  5719.    * are listening. We maintain the master state of download operations HERE,
  5720.    * not in the front end, because if the user closes the extension or theme
  5721.    * managers during the downloads we need to maintain state and not terminate
  5722.    * the download/install process.
  5723.    *
  5724.    * @param   transaction
  5725.    *          The ItemDownloadTransaction object receiving the download
  5726.    *          notifications from XPInstall.
  5727.    * @param   addon
  5728.    *          An object representing nsIUpdateItem for the addon being updated
  5729.    * @param   state
  5730.    *          The state we are entering
  5731.    * @param   value
  5732.    *          ???
  5733.    */
  5734.   onStateChange: function(transaction, addon, state, value) {
  5735.     var ds = this.datasource;
  5736.     var id = addon.id != addon.xpiURL ? PREFIX_ITEM_URI + addon.id : addon.xpiURL;
  5737.     const nsIXPIProgressDialog = Ci.nsIXPIProgressDialog;
  5738.     switch (state) {
  5739.     case nsIXPIProgressDialog.DOWNLOAD_START:
  5740.       ds.updateDownloadState(id, "downloading");
  5741.       for (var i = 0; i < this._installListeners.length; ++i)
  5742.         this._installListeners[i].onDownloadStarted(addon);
  5743.       break;
  5744.     case nsIXPIProgressDialog.DOWNLOAD_DONE:
  5745.       for (var i = 0; i < this._installListeners.length; ++i)
  5746.         this._installListeners[i].onDownloadEnded(addon);
  5747.       break;
  5748.     case nsIXPIProgressDialog.INSTALL_START:
  5749.       ds.updateDownloadState(id, "finishing");
  5750.       ds.updateDownloadProgress(id, null);
  5751.       break;
  5752.     case nsIXPIProgressDialog.INSTALL_DONE:
  5753.       --this._downloadCount;
  5754.       // From nsInstall.h
  5755.       // SUCCESS        = 0
  5756.       // USER_CANCELLED = -210
  5757.       if (value != 0 && value != -210 && id != addon.xpiURL) {
  5758.         ds.updateDownloadState(id, "failure");
  5759.         ds.updateDownloadProgress(id, null);
  5760.       }
  5761.       transaction.removeDownload(addon.xpiURL);
  5762.       // A successful install will be passing notifications via installItemFromFile
  5763.       if (value != 0) {
  5764.         for (var i = 0; i < this._installListeners.length; ++i)
  5765.           this._installListeners[i].onInstallEnded(addon, value);
  5766.       }
  5767.       break;
  5768.     case nsIXPIProgressDialog.DIALOG_CLOSE:
  5769.       for (var i = 0; i < this._transactions.length; ++i) {
  5770.         if (this._transactions[i].id == transaction.id) {
  5771.           this._transactions.splice(i, 1);
  5772.           // Remove the observers when all transactions have completed.
  5773.           if (this._transactions.length == 0) {
  5774.             gOS.removeObserver(this, "offline-requested");
  5775.             gOS.removeObserver(this, "quit-application-requested");
  5776.  
  5777.             // If there are no compatibility checks running then the install
  5778.             // operations are complete.
  5779.             if (this._compatibilityCheckCount == 0) {
  5780.               for (var i = 0; i < this._installListeners.length; ++i)
  5781.                 this._installListeners[i].onInstallsCompleted();
  5782.             }
  5783.           }
  5784.           break;
  5785.         }
  5786.       }
  5787.       // Remove any remaining downloads from this transaction
  5788.       transaction.removeAllDownloads();
  5789.       break;
  5790.     }
  5791.   },
  5792.  
  5793.   onProgress: function(addon, value, maxValue) {
  5794.     for (var i = 0; i < this._installListeners.length; ++i)
  5795.       this._installListeners[i].onDownloadProgress(addon, value, maxValue);
  5796.  
  5797.     var id = addon.id != addon.xpiURL ? PREFIX_ITEM_URI + addon.id : addon.xpiURL;
  5798.     var progress = Math.round((value / maxValue) * 100);
  5799.     this.datasource.updateDownloadProgress(id, progress);
  5800.   },
  5801.  
  5802.   _installListeners: [],
  5803.   addInstallListener: function(listener) {
  5804.     for (var i = 0; i < this._installListeners.length; ++i) {
  5805.       if (this._installListeners[i] == listener)
  5806.         return i;
  5807.     }
  5808.     this._installListeners.push(listener);
  5809.     return this._installListeners.length - 1;
  5810.   },
  5811.  
  5812.   removeInstallListenerAt: function(index) {
  5813.     this._installListeners.splice(index, 1);
  5814.   },
  5815.  
  5816.   /**
  5817.    * The Extensions RDF Datasource
  5818.    */
  5819.   _ds: null,
  5820.   _ptr: null,
  5821.  
  5822.   /**
  5823.    * Loads the Extensions Datasource. This should not be called unless:
  5824.    * - a piece of Extensions UI is being shown, or
  5825.    * - on startup and there has been a change to an Install Location
  5826.    * ... it should NOT be called on every startup!
  5827.    */
  5828.   _ensureDS: function() {
  5829.     if (!this._ds) {
  5830.       this._ds = new ExtensionsDataSource(this);
  5831.       if (this._ds) {
  5832.         this._ds.loadExtensions();
  5833.         this._ptr = getContainer(this._ds, this._ds._itemRoot).DataSource;
  5834.         gRDF.RegisterDataSource(this._ptr, true);
  5835.       }
  5836.     }
  5837.   },
  5838.  
  5839.   /**
  5840.    * See nsIExtensionManager.idl
  5841.    */
  5842.   get datasource() {
  5843.     this._ensureDS();
  5844.     return this._ds.QueryInterface(Ci.nsIRDFDataSource);
  5845.   },
  5846.  
  5847.   // nsIClassInfo
  5848.   flags: Ci.nsIClassInfo.SINGLETON,
  5849.   implementationLanguage: Ci.nsIProgrammingLanguage.JAVASCRIPT,
  5850.   getHelperForLanguage: function(language) null,
  5851.   getInterfaces: function(count) {
  5852.     var interfaces = [Ci.nsIExtensionManager, Ci.nsIObserver];
  5853.     count.value = interfaces.length;
  5854.     return interfaces;
  5855.   },
  5856.  
  5857.   classDescription: "Extension Manager",
  5858.   contractID: "@mozilla.org/extensions/manager;1",
  5859.   classID: Components.ID("{8A115FAA-7DCB-4e8f-979B-5F53472F51CF}"),
  5860.   _xpcom_categories: [{ category: "app-startup", service: true }],
  5861.   _xpcom_factory: EmFactory,
  5862.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIExtensionManager,
  5863.                                          Ci.nsITimerCallback,
  5864.                                          Ci.nsIObserver,
  5865.                                          Ci.nsIClassInfo])
  5866. };
  5867.  
  5868. /**
  5869.  * This object implements nsIXPIProgressDialog and represents a collection of
  5870.  * XPI/JAR download and install operations. There is one
  5871.  * ItemDownloadTransaction per back-end XPInstallManager object. We maintain
  5872.  * a collection of separate transaction objects because it's possible to have
  5873.  * multiple separate XPInstall download/install operations going on
  5874.  * simultaneously, each with its own XPInstallManager instance. For instance
  5875.  * you could start downloading two extensions and then download a theme. Each
  5876.  * of these operations would open the appropriate FE and have to be able to
  5877.  * track each operation independently.
  5878.  *
  5879.  * @constructor
  5880.  * @param   manager
  5881.  *          The extension manager creating this transaction
  5882.  * @param   id
  5883.  *          The integer identifier of this transaction
  5884.  */
  5885. function ItemDownloadTransaction(manager, id) {
  5886.   this._manager = manager;
  5887.   this._downloads = [];
  5888.   this.id = id;
  5889. }
  5890. ItemDownloadTransaction.prototype = {
  5891.   _manager    : null,
  5892.   _downloads  : [],
  5893.   id          : -1,
  5894.  
  5895.   /**
  5896.    * Add a download to this transaction
  5897.    * @param   addon
  5898.    *          An object implementing nsIUpdateItem for the item to be downloaded
  5899.    */
  5900.   addDownload: function(addon) {
  5901.     this._downloads.push({ addon: addon, waiting: true });
  5902.     this._manager.datasource.addDownload(addon);
  5903.   },
  5904.  
  5905.   /**
  5906.    * Removes a download from this transaction
  5907.    * @param   url
  5908.    *          The URL to remove
  5909.    */
  5910.   removeDownload: function(url) {
  5911.     this._manager.datasource.removeDownload(url);
  5912.   },
  5913.  
  5914.   /**
  5915.    * Remove all downloads from this transaction
  5916.    */
  5917.   removeAllDownloads: function() {
  5918.     for (var i = 0; i < this._downloads.length; ++i) {
  5919.       var addon = this._downloads[i].addon;
  5920.       this.removeDownload(addon.xpiURL);
  5921.     }
  5922.   },
  5923.  
  5924.   /**
  5925.    * Determine if this transaction is handling the download of a url.
  5926.    * @param   url
  5927.    *          The URL to look for
  5928.    * @returns true if this transaction is downloading the supplied url.
  5929.    */
  5930.   containsURL: function(url) {
  5931.     for (var i = 0; i < this._downloads.length; ++i) {
  5932.       if (this._downloads[i].addon.xpiURL == url)
  5933.         return true;
  5934.     }
  5935.     return false;
  5936.   },
  5937.  
  5938.   /**
  5939.    * See nsIXPIProgressDialog.idl
  5940.    */
  5941.   onStateChange: function(index, state, value) {
  5942.     this._manager.onStateChange(this, this._downloads[index].addon,
  5943.                                 state, value);
  5944.   },
  5945.  
  5946.   /**
  5947.    * See nsIXPIProgressDialog.idl
  5948.    */
  5949.   onProgress: function(index, value, maxValue) {
  5950.     this._manager.onProgress(this._downloads[index].addon, value, maxValue);
  5951.   },
  5952.  
  5953.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIXPIProgressDialog])
  5954. };
  5955.  
  5956. /**
  5957.  * A listener object that watches the background update check and notifies the
  5958.  * user of any updates found.
  5959.  */
  5960. function BackgroundUpdateCheckListener(datasource) {
  5961.   this._emDS = datasource;
  5962. }
  5963. BackgroundUpdateCheckListener.prototype = {
  5964.   _updateCount: 0,
  5965.   _emDS: null,
  5966.  
  5967.   // nsIObserver implementation
  5968.   observe: function(aSubject, aTopic, aData) {
  5969.     if (aTopic != "alertclickcallback")
  5970.       return;
  5971.  
  5972.     var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
  5973.              getService(Ci.nsIWindowMediator);
  5974.     var win = wm.getMostRecentWindow("Extension:Manager");
  5975.     if (win) {
  5976.       win.focus();
  5977.       win.showView("updates");
  5978.       // Don't show the update notification on next startup
  5979.       gPref.setBoolPref(PREF_UPDATE_NOTIFYUSER, false);
  5980.     }
  5981.     else {
  5982.       const EMURL = "chrome://mozapps/content/extensions/extensions.xul";
  5983.       const EMFEATURES = "chrome,menubar,extra-chrome,toolbar,dialog=no,resizable";
  5984.  
  5985.       var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
  5986.                getService(Ci.nsIWindowWatcher);
  5987.       var param = Cc["@mozilla.org/supports-array;1"].
  5988.                   createInstance(Ci.nsISupportsArray);
  5989.       var arg = Cc["@mozilla.org/supports-string;1"].
  5990.                 createInstance(Ci.nsISupportsString);
  5991.       arg.data = "updates";
  5992.       param.AppendElement(arg);
  5993.       ww.openWindow(null, EMURL, null, EMFEATURES, param);
  5994.     }
  5995.   },
  5996.   
  5997.   // nsIAddonUpdateCheckListener implementation
  5998.   onUpdateStarted: function() {
  5999.   },
  6000.  
  6001.   onUpdateEnded: function() {
  6002.     if (this._updateCount > 0 && Cc["@mozilla.org/alerts-service;1"]) {
  6003.       var extensionStrings = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  6004.       var title = extensionStrings.GetStringFromName("updateNotificationTitle");
  6005.       var text;
  6006.       if (this._updateCount > 1)
  6007.         text = extensionStrings.formatStringFromName("multipleUpdateNotificationText",
  6008.                                                      [BundleManager.appName, this._updateCount], 2);
  6009.       else
  6010.         text = extensionStrings.formatStringFromName("updateNotificationText",
  6011.                                                      [BundleManager.appName], 1);
  6012.  
  6013.       try {
  6014.         var notifier = Cc["@mozilla.org/alerts-service;1"].
  6015.                        getService(Ci.nsIAlertsService);
  6016.         notifier.showAlertNotification(URI_GENERIC_ICON_XPINSTALL,
  6017.                                        title, text, true, "", this);
  6018.       }
  6019.       catch (e) {
  6020.         LOG("Failed to retrieve alerts service, probably an unsupported " +
  6021.             "platform - " + e);
  6022.       }
  6023.     }
  6024.   },
  6025.  
  6026.   onAddonUpdateStarted: function(item) {
  6027.   },
  6028.  
  6029.   onAddonUpdateEnded: function(item, status) {
  6030.     if (status == Ci.nsIAddonUpdateCheckListener.STATUS_UPDATE) {
  6031.       var lastupdate = this._emDS.getItemProperty(item.id, "availableUpdateVersion");
  6032.       if (lastupdate != item.version) {
  6033.         gPref.setBoolPref(PREF_UPDATE_NOTIFYUSER, true);
  6034.         this._updateCount++;
  6035.       }
  6036.     }
  6037.   }
  6038. };
  6039.  
  6040.  
  6041. /**
  6042.  * A listener object to the update check process that routes notifications to
  6043.  * the right places and keeps the datasource up to date.
  6044.  */
  6045. function AddonUpdateCheckListener(listener, datasource) {
  6046.   this._listener = listener;
  6047.   this._ds = datasource;
  6048. }
  6049. AddonUpdateCheckListener.prototype = {
  6050.   _listener: null,
  6051.   _ds: null,
  6052.  
  6053.   onUpdateStarted: function() {
  6054.     if (this._listener)
  6055.       this._listener.onUpdateStarted();
  6056.     this._ds.onUpdateStarted();
  6057.   },
  6058.  
  6059.   onUpdateEnded: function() {
  6060.     if (this._listener)
  6061.       this._listener.onUpdateEnded();
  6062.     this._ds.onUpdateEnded();
  6063.   },
  6064.  
  6065.   onAddonUpdateStarted: function(addon) {
  6066.     if (this._listener)
  6067.       this._listener.onAddonUpdateStarted(addon);
  6068.     this._ds.onAddonUpdateStarted(addon);
  6069.   },
  6070.  
  6071.   onAddonUpdateEnded: function(addon, status) {
  6072.     if (this._listener)
  6073.       this._listener.onAddonUpdateEnded(addon, status);
  6074.     this._ds.onAddonUpdateEnded(addon, status);
  6075.   }
  6076. };
  6077.  
  6078. ///////////////////////////////////////////////////////////////////////////////
  6079. //
  6080. // ExtensionItemUpdater
  6081. //
  6082. function ExtensionItemUpdater(aEM)
  6083. {
  6084.   this._emDS = aEM._ds;
  6085.   this._em = aEM;
  6086.  
  6087.   getVersionChecker();
  6088. }
  6089.  
  6090. ExtensionItemUpdater.prototype = {
  6091.   _emDS               : null,
  6092.   _em                 : null,
  6093.   _updateCheckType    : 0,
  6094.   _items              : [],
  6095.   _listener           : null,
  6096.  
  6097.   /* ExtensionItemUpdater
  6098. //@line 6108 "e:\builds\tinderbox\XR-Trunk\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  6099.   */
  6100.   checkForUpdates: function(aItems, aItemCount, aUpdateCheckType,
  6101.                             aListener) {
  6102.     this._listener = new AddonUpdateCheckListener(aListener, this._emDS);
  6103.     if (this._listener)
  6104.       this._listener.onUpdateStarted();
  6105.     this._updateCheckType = aUpdateCheckType;
  6106.     this._items = aItems;
  6107.     this._responseCount = aItemCount;
  6108.  
  6109.     // This is the number of extensions/themes/etc that we found updates for.
  6110.     this._updateCount = 0;
  6111.  
  6112.     for (var i = 0; i < aItemCount; ++i) {
  6113.       var e = this._items[i];
  6114.       if (this._listener)
  6115.         this._listener.onAddonUpdateStarted(e);
  6116.       (new RDFItemUpdater(this)).checkForUpdates(e, aUpdateCheckType);
  6117.     }
  6118.  
  6119.     if (this._listener && aItemCount == 0)
  6120.       this._listener.onUpdateEnded();
  6121.   },
  6122.  
  6123.   /////////////////////////////////////////////////////////////////////////////
  6124.   // ExtensionItemUpdater
  6125.   _applyVersionUpdates: function(aLocalItem, aRemoteItem) {
  6126.     var targetAppInfo = this._emDS.getTargetApplicationInfo(aLocalItem.id, this._emDS);
  6127.     // If targetAppInfo is null this is for a new install. If the local item's
  6128.     // maxVersion does not equal the targetAppInfo maxVersion then this is for
  6129.     // an upgrade. In both of these cases return true if the remotely specified
  6130.     // maxVersion is greater than the local item's maxVersion.
  6131.     if (!targetAppInfo ||
  6132.         gVersionChecker.compare(aLocalItem.maxAppVersion, targetAppInfo.maxVersion) != 0) {
  6133.       if (gVersionChecker.compare(aLocalItem.maxAppVersion, aRemoteItem.maxAppVersion) < 0)
  6134.         return true;
  6135.       else
  6136.         return false;
  6137.     }
  6138.  
  6139.     if (gVersionChecker.compare(targetAppInfo.maxVersion, aRemoteItem.maxAppVersion) < 0) {
  6140.       // Remotely specified maxVersion is newer than the maxVersion
  6141.       // for the installed Extension. Apply that change to the datasources.
  6142.       this._emDS.setTargetApplicationInfo(aLocalItem.id,
  6143.                                           aRemoteItem.targetAppID,
  6144.                                           aRemoteItem.minAppVersion,
  6145.                                           aRemoteItem.maxAppVersion,
  6146.                                           null);
  6147.  
  6148.       // If we got here through |checkForMismatches|, this extension has
  6149.       // already been disabled, re-enable it.
  6150.       var op = StartupCache.entries[aLocalItem.installLocationKey][aLocalItem.id].op;
  6151.       if (op == OP_NEEDS_DISABLE ||
  6152.           this._emDS.getItemProperty(aLocalItem.id, "appDisabled") == "true")
  6153.         this._em._appEnableItem(aLocalItem.id);
  6154.       return true;
  6155.     }
  6156.     else if (this._updateCheckType == Ci.nsIExtensionManager.UPDATE_SYNC_COMPATIBILITY)
  6157.       this._emDS.setTargetApplicationInfo(aLocalItem.id,
  6158.                                           aRemoteItem.targetAppID,
  6159.                                           aRemoteItem.minAppVersion,
  6160.                                           aRemoteItem.maxAppVersion,
  6161.                                           null);
  6162.     return false;
  6163.   },
  6164.  
  6165.   /**
  6166.    * Checks whether a discovered update is valid for install
  6167.    * @param   aLocalItem
  6168.    *          The already installed nsIUpdateItem that the update is for
  6169.    * @param   aRemoteItem
  6170.    *          The nsIUpdateItem we are trying to update to
  6171.    *
  6172.    * @returns true if the item is compatible and is not blocklisted.
  6173.    *          false if the item is not compatible or is blocklisted.
  6174.    */
  6175.   _isValidUpdate: function _isValidUpdate(aLocalItem, aRemoteItem) {
  6176.     var appExtensionsVersion = (aRemoteItem.targetAppID != TOOLKIT_ID) ?
  6177.                                gApp.version :
  6178.                                gApp.platformVersion;
  6179.  
  6180.     var min = aRemoteItem.minAppVersion;
  6181.     var max = aRemoteItem.maxAppVersion;
  6182.     // Check if the update will only run on a newer version of the application.
  6183.     if (!min || gVersionChecker.compare(appExtensionsVersion, min) < 0)
  6184.       return false;
  6185.  
  6186.     // Check if the update will only run on an older version of the application.
  6187.     if (!max || gVersionChecker.compare(appExtensionsVersion, max) > 0)
  6188.       return false;
  6189.  
  6190.     if (!gBlocklist)
  6191.       gBlocklist = Cc["@mozilla.org/extensions/blocklist;1"].
  6192.                    getService(Ci.nsIBlocklistService);
  6193.     if (gBlocklist.isAddonBlocklisted(aLocalItem.id, aRemoteItem.version,
  6194.                                       null, null))
  6195.       return false;
  6196.  
  6197.     return true;
  6198.   },
  6199.  
  6200.   checkForDone: function(item, status) {
  6201.     if (this._listener) {
  6202.       try {
  6203.         this._listener.onAddonUpdateEnded(item, status);
  6204.       }
  6205.       catch (e) {
  6206.         LOG("ExtensionItemUpdater:checkForDone: Failure in listener's onAddonUpdateEnded: " + e);
  6207.       }
  6208.     }
  6209.     if (--this._responseCount == 0 && this._listener) {
  6210.       try {
  6211.         this._listener.onUpdateEnded();
  6212.       }
  6213.       catch (e) {
  6214.         LOG("ExtensionItemUpdater:checkForDone: Failure in listener's onUpdateEnded: " + e);
  6215.       }
  6216.     }
  6217.   },
  6218. };
  6219.  
  6220. /**
  6221.  * Replaces %...% strings in an addon url (update and updateInfo) with
  6222.  * appropriate values.
  6223.  * @param   aItem
  6224.  *          The nsIUpdateItem representing the item
  6225.  * @param   aURI
  6226.  *          The uri to escape
  6227.  * @param   aDS
  6228.  *          The extensions datasource
  6229.  *
  6230.  * @returns the appropriately escaped uri.
  6231.  */
  6232. function escapeAddonURI(aItem, aURI, aDS)
  6233. {
  6234.   var itemStatus = "userEnabled";
  6235.   if (aDS.getItemProperty(aItem.id, "userDisabled") == "true" ||
  6236.       aDS.getItemProperty(aItem.id, "userDisabled") == OP_NEEDS_ENABLE)
  6237.     itemStatus = "userDisabled";
  6238.   else if (aDS.getItemProperty(aItem.id, "type") == Ci.nsIUpdateItem.TYPE_THEME) {
  6239.     var currentSkin = gPref.getCharPref(PREF_GENERAL_SKINS_SELECTEDSKIN);
  6240.     if (aDS.getItemProperty(aItem.id, "internalName") != currentSkin)
  6241.       itemStatus = "userDisabled";
  6242.   }
  6243.  
  6244.   if (aDS.getItemProperty(aItem.id, "compatible") == "false")
  6245.     itemStatus += ",incompatible";
  6246.   if (aDS.getItemProperty(aItem.id, "blocklisted") == "true")
  6247.     itemStatus += ",blocklisted";
  6248.   if (aDS.getItemProperty(aItem.id, "satisfiesDependencies") == "false")
  6249.     itemStatus += ",needsDependencies";
  6250.  
  6251.   aURI = aURI.replace(/%ITEM_ID%/g, aItem.id);
  6252.   aURI = aURI.replace(/%ITEM_VERSION%/g, aItem.version);
  6253.   aURI = aURI.replace(/%ITEM_MAXAPPVERSION%/g, aItem.maxAppVersion);
  6254.   aURI = aURI.replace(/%ITEM_STATUS%/g, itemStatus);
  6255.   aURI = aURI.replace(/%APP_ID%/g, gApp.ID);
  6256.   aURI = aURI.replace(/%APP_VERSION%/g, gApp.version);
  6257.   aURI = aURI.replace(/%REQ_VERSION%/g, 1);
  6258.   aURI = aURI.replace(/%APP_OS%/g, gOSTarget);
  6259.   aURI = aURI.replace(/%APP_ABI%/g, gXPCOMABI);
  6260.   aURI = aURI.replace(/%APP_LOCALE%/g, gLocale);
  6261.  
  6262.   // Replace custom parameters (names of custom parameters must have at
  6263.   // least 3 characters to prevent lookups for something like %D0%C8)
  6264.   var catMan = null;
  6265.   aURI = aURI.replace(/%(\w{3,})%/g, function(match, param) {
  6266.     if (!catMan) {
  6267.       catMan = Cc["@mozilla.org/categorymanager;1"].
  6268.                getService(Ci.nsICategoryManager);
  6269.     }
  6270.  
  6271.     try {
  6272.       var contractID = catMan.getCategoryEntry(CATEGORY_UPDATE_PARAMS, param);
  6273.       var paramHandler = Cc[contractID].
  6274.                          getService(Ci.nsIPropertyBag2);
  6275.       return paramHandler.getPropertyAsAString(param);
  6276.     }
  6277.     catch(e) {
  6278.       return match;
  6279.     }
  6280.   });
  6281.  
  6282.   // escape() does not properly encode + symbols in any embedded FVF strings.
  6283.   return aURI.replace(/\+/g, "%2B");
  6284. }
  6285.  
  6286. function RDFItemUpdater(aUpdater) {
  6287.   this._updater = aUpdater;
  6288. }
  6289.  
  6290. RDFItemUpdater.prototype = {
  6291.   _updater            : null,
  6292.   _updateCheckType    : 0,
  6293.   _item               : null,
  6294.  
  6295.   checkForUpdates: function(aItem, aUpdateCheckType) {
  6296.     // A preference setting can disable updating for this item
  6297.     try {
  6298.       if (!gPref.getBoolPref(PREF_EM_ITEM_UPDATE_ENABLED.replace(/%UUID%/, aItem.id))) {
  6299.         var status = Ci.nsIAddonUpdateCheckListener.STATUS_DISABLED;
  6300.         this._updater.checkForDone(aItem, status);
  6301.         return;
  6302.       }
  6303.     }
  6304.     catch (e) { }
  6305.  
  6306.     // Items managed by the app are not checked for updates.
  6307.     var emDS = this._updater._emDS;
  6308.     if (emDS.getItemProperty(aItem.id, "appManaged") == "true") {
  6309.       var status = Ci.nsIAddonUpdateCheckListener.STATUS_APP_MANAGED;
  6310.       this._updater.checkForDone(aItem, status);
  6311.       return;
  6312.     }
  6313.  
  6314.     // Items that have a pending install, uninstall, or upgrade are not checked
  6315.     // for updates.
  6316.     var opType = emDS.getItemProperty(aItem.id, "opType");
  6317.     if (opType) {
  6318.       var status = Ci.nsIAddonUpdateCheckListener.STATUS_PENDING_OP;
  6319.       this._updater.checkForDone(aItem, status);
  6320.       return;
  6321.     }
  6322.  
  6323.     var installLocation = InstallLocations.get(emDS.getInstallLocationKey(aItem.id));
  6324.     // Don't check items for updates that are managed independently
  6325.     if (installLocation && installLocation.itemIsManagedIndependently(aItem.id)) {
  6326.       var status = Ci.nsIAddonUpdateCheckListener.STATUS_NOT_MANAGED;
  6327.       this._updater.checkForDone(aItem, status);
  6328.       return;
  6329.     }
  6330.  
  6331.     // Don't check items for updates if the location can't be written to except
  6332.     // when performing a version only update.
  6333.     if ((aUpdateCheckType == Ci.nsIExtensionManager.UPDATE_CHECK_NEWVERSION) &&
  6334.         (!installLocation || !installLocation.canAccess)) {
  6335.       var status = Ci.nsIAddonUpdateCheckListener.STATUS_READ_ONLY;
  6336.       this._updater.checkForDone(aItem, status);
  6337.       return;
  6338.     }
  6339.  
  6340.     this._updateCheckType = aUpdateCheckType;
  6341.     this._item = aItem;
  6342.  
  6343.     // Look for a custom update URI: 1) supplied by a pref, 2) supplied by the
  6344.     // install manifest, 3) the default configuration
  6345.     try {
  6346.       var dsURI = gPref.getComplexValue(PREF_EM_ITEM_UPDATE_URL.replace(/%UUID%/, aItem.id),
  6347.                                         Ci.nsIPrefLocalizedString).data;
  6348.     }
  6349.     catch (e) { }
  6350.     if (!dsURI)
  6351.       dsURI = aItem.updateRDF;
  6352.     if (!dsURI)
  6353.       dsURI = gPref.getCharPref(PREF_UPDATE_DEFAULT_URL);
  6354.  
  6355.     dsURI = escapeAddonURI(aItem, dsURI, emDS);
  6356.  
  6357.     // Verify that the URI provided is valid
  6358.     try {
  6359.       var uri = newURI(dsURI);
  6360.     }
  6361.     catch (e) {
  6362.       LOG("RDFItemUpdater:checkForUpdates: There was an error loading the \r\n" +
  6363.           " update datasource for: " + dsURI + ", item = " + aItem.id + ", error: " + e);
  6364.       this._updater.checkForDone(aItem,
  6365.                                  Ci.nsIAddonUpdateCheckListener.STATUS_FAILURE);
  6366.       return;
  6367.     }
  6368.  
  6369.     LOG("RDFItemUpdater:checkForUpdates sending a request to server for: " +
  6370.         uri.spec + ", item = " + aItem.objectSource);
  6371.  
  6372.     var request = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].
  6373.                   createInstance(Ci.nsIXMLHttpRequest);
  6374.     request.open("GET", uri.spec, true);
  6375.     request.channel.notificationCallbacks = new BadCertHandler();
  6376.     request.overrideMimeType("text/xml");
  6377.     request.channel.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE;
  6378.  
  6379.     var self = this;
  6380.     request.onerror     = function(event) { self.onXMLError(event, aItem);    };
  6381.     request.onload      = function(event) { self.onXMLLoad(event, aItem);     };
  6382.     request.send(null);
  6383.   },
  6384.  
  6385.   onXMLLoad: function(aEvent, aItem) {
  6386.     var request = aEvent.target;
  6387.     try {
  6388.       checkCert(request.channel);
  6389.     }
  6390.     catch (e) {
  6391.       // This may be overly restrictive in two cases: corporate installations
  6392.       // with a corporate update server using an in-house CA cert (installed
  6393.       // but not "built-in") and lone developers hosting their updates on a
  6394.       // site with a self-signed cert (permanently accepted, otherwise the
  6395.       // BadCertHandler would prevent getting this far). Update checks will
  6396.       // fail in both these scenarios.
  6397.       // How else can we protect the vast majority of updates served from AMO
  6398.       // from the spoofing attack described in bug 340198 while allowing those
  6399.       // other cases? A "hackme" pref? Domain-control certs are cheap, getting
  6400.       // one should not be a barrier in either case.
  6401.       LOG("RDFItemUpdater::onXMLLoad: " + e);
  6402.       this._updater.checkForDone(aItem,
  6403.                                  Ci.nsIAddonUpdateCheckListener.STATUS_FAILURE);
  6404.       return;
  6405.     }
  6406.     var responseXML = request.responseXML;
  6407.  
  6408.     // If the item does not have an update RDF and returns an error it is not
  6409.     // treated as a failure since all items without an updateURL are checked
  6410.     // for updates on AMO even if they are not hosted there.
  6411.     if (!responseXML || responseXML.documentElement.namespaceURI == XMLURI_PARSE_ERROR ||
  6412.         (request.status != 200 && request.status != 0)) {
  6413.       this._updater.checkForDone(aItem, (aItem.updateRDF ? Ci.nsIAddonUpdateCheckListener.STATUS_FAILURE :
  6414.                                                            Ci.nsIAddonUpdateCheckListener.STATUS_NONE));
  6415.       return;
  6416.     }
  6417.  
  6418.     var rdfParser = Cc["@mozilla.org/rdf/xml-parser;1"].
  6419.                     createInstance(Ci.nsIRDFXMLParser)
  6420.     var ds = Cc["@mozilla.org/rdf/datasource;1?name=in-memory-datasource"].
  6421.              createInstance(Ci.nsIRDFDataSource);
  6422.     rdfParser.parseString(ds, request.channel.URI, request.responseText);
  6423.  
  6424.     this.onDatasourceLoaded(ds, aItem);
  6425.   },
  6426.  
  6427.   onXMLError: function(aEvent, aItem) {
  6428.     try {
  6429.       var request = aEvent.target;
  6430.       // the following may throw (e.g. a local file or timeout)
  6431.       var status = request.status;
  6432.     }
  6433.     catch (e) {
  6434.       request = aEvent.target.channel.QueryInterface(Ci.nsIRequest);
  6435.       status = request.status;
  6436.     }
  6437.     // this can fail when a network connection is not present.
  6438.     try {
  6439.       var statusText = request.statusText;
  6440.     }
  6441.     catch (e) {
  6442.       status = 0;
  6443.     }
  6444.     // When status is 0 we don't have a valid channel.
  6445.     if (status == 0)
  6446.       statusText = "nsIXMLHttpRequest channel unavailable";
  6447.  
  6448.     LOG("RDFItemUpdater:onError: There was an error loading the \r\n" +
  6449.         "the update datasource for item " + aItem.id + ", error: " + statusText);
  6450.     this._updater.checkForDone(aItem,
  6451.                                Ci.nsIAddonUpdateCheckListener.STATUS_FAILURE);
  6452.   },
  6453.  
  6454.   onDatasourceLoaded: function(aDatasource, aLocalItem) {
  6455.     /*
  6456. //@line 6506 "e:\builds\tinderbox\XR-Trunk\WINNT_5.2_Depend\mozilla\toolkit\mozapps\extensions\src\nsExtensionManager.js.in"
  6457.     */
  6458.     if (!aDatasource.GetAllResources().hasMoreElements()) {
  6459.       LOG("RDFItemUpdater:onDatasourceLoaded: Datasource empty.\r\n" +
  6460.           "If you are an Extension developer and were expecting there to be\r\n" +
  6461.           "updates, this could mean any number of things, since the RDF system\r\n" +
  6462.           "doesn't give up much in the way of information when the load fails.\r\n" +
  6463.           "\r\nTry checking that: \r\n" +
  6464.           " 1. Your remote RDF file exists at the location.\r\n" +
  6465.           " 2. Your RDF file is valid XML (starts with <?xml version=\"1.0\"?>\r\n" +
  6466.           "    and loads in Firefox displaying pretty printed like other XML documents\r\n" +
  6467.           " 3. Your server is sending the data in the correct MIME\r\n" +
  6468.           "    type (text/xml)");
  6469.     }      
  6470.  
  6471.     // If we have an update key then the update manifest must be signed
  6472.     if (aLocalItem.updateKey) {
  6473.       var extensionRes = gRDF.GetResource(getItemPrefix(aLocalItem.type) + aLocalItem.id);
  6474.       LOG(extensionRes.Value);
  6475.       var signature = this._getPropertyFromResource(aDatasource, extensionRes, "signature", null);
  6476.       if (signature) {
  6477.         var serializer = new RDFSerializer();
  6478.         try {
  6479.           var updateString = serializer.serializeResource(aDatasource, extensionRes);
  6480.           var verifier = Cc["@mozilla.org/security/datasignatureverifier;1"].
  6481.                          getService(Ci.nsIDataSignatureVerifier);
  6482.           try {
  6483.             if (!verifier.verifyData(updateString, signature, aLocalItem.updateKey)) {
  6484.               LOG("RDFItemUpdater:onDatasourceLoaded: Update manifest for " +
  6485.                   aLocalItem.id + " failed signature check.");
  6486.               this._updater.checkForDone(aLocalItem, Ci.nsIAddonUpdateCheckListener.STATUS_FAILURE);
  6487.               return;
  6488.             }
  6489.           }
  6490.           catch (e) {
  6491.             LOG("RDFItemUpdater:onDatasourceLoaded: Failed to verify signature for " +
  6492.                 aLocalItem.id + ". This indicates a malformed update key or signature.");
  6493.             this._updater.checkForDone(aLocalItem, Ci.nsIAddonUpdateCheckListener.STATUS_FAILURE);
  6494.             return;
  6495.           }
  6496.         }
  6497.         catch (e) {
  6498.           LOG("RDFItemUpdater:onDatasourceLoaded: Failed to generate signature " +
  6499.               "string for " + aLocalItem.id + ". Serializer threw " + e);
  6500.           this._updater.checkForDone(aLocalItem, Ci.nsIAddonUpdateCheckListener.STATUS_FAILURE);
  6501.           return;
  6502.         }
  6503.       }
  6504.       else {
  6505.         LOG("RDFItemUpdater:onDatasourceLoaded: Update manifest for " +
  6506.             aLocalItem.id + " did not contain a signature.");
  6507.         this._updater.checkForDone(aLocalItem, Ci.nsIAddonUpdateCheckListener.STATUS_FAILURE);
  6508.         return;
  6509.       }
  6510.     }
  6511.     /* If there is no updateKey either the update was over SSL, or it is an old
  6512.      * addon that we are allowing a grace update. */
  6513.  
  6514.     // Parse the response RDF
  6515.     var newerItem, sameItem;
  6516.  
  6517.     // Firefox 1.0PR+ update.rdf format
  6518.     if (this._updateCheckType == Ci.nsIExtensionManager.UPDATE_CHECK_NEWVERSION) {
  6519.       // Look for newer versions of this item, we only do this in "normal"
  6520.       // mode... see comment by ExtensionItemUpdater_checkForUpdates
  6521.       // about how we do this in all cases but Install Phone Home - which
  6522.       // only needs to do a version check.
  6523.       newerItem = this._parseV20UpdateInfo(aDatasource, aLocalItem,
  6524.                                            Ci.nsIExtensionManager.UPDATE_CHECK_NEWVERSION);
  6525.  
  6526.       if (newerItem) {
  6527.         ++this._updater._updateCount;
  6528.         LOG("RDFItemUpdater:onDatasourceLoaded: Found a newer version of this item:\r\n" +
  6529.             newerItem.objectSource);
  6530.       }
  6531.     }
  6532.  
  6533.     // Now look for updated version compatibility metadata for the currently
  6534.     // installed version...
  6535.     sameItem = this._parseV20UpdateInfo(aDatasource, aLocalItem,
  6536.                                         Ci.nsIExtensionManager.UPDATE_CHECK_COMPATIBILITY);
  6537.  
  6538.     if (sameItem) {
  6539.       // Install-time updates are not written to the DS because there is no
  6540.       // entry yet, EM just uses the notifications to ascertain (by hand)
  6541.       // whether or not there is a remote maxVersion tweak that makes the
  6542.       // item being installed compatible.
  6543.       if (!this._updater._applyVersionUpdates(aLocalItem, sameItem))
  6544.         sameItem = null;
  6545.       else
  6546.         LOG("RDFItemUpdater:onDatasourceLoaded: Found info about the installed\r\n" +
  6547.             "version of this item: " + sameItem.objectSource);
  6548.     }
  6549.     var item = null, status = Ci.nsIAddonUpdateCheckListener.STATUS_NONE;
  6550.     if (this._updateCheckType == Ci.nsIExtensionManager.UPDATE_CHECK_NEWVERSION
  6551.         && newerItem) {
  6552.       item = newerItem;
  6553.       status = Ci.nsIAddonUpdateCheckListener.STATUS_UPDATE;
  6554.     }
  6555.     else if (sameItem) {
  6556.       item = sameItem;
  6557.       status = Ci.nsIAddonUpdateCheckListener.STATUS_VERSIONINFO;
  6558.     }
  6559.     else {
  6560.       item = aLocalItem;
  6561.       status = Ci.nsIAddonUpdateCheckListener.STATUS_NO_UPDATE;
  6562.     }
  6563.     // Only one call of this._updater.checkForDone is needed for RDF
  6564.     // responses, since there is only one response per item.
  6565.     this._updater.checkForDone(item, status);
  6566.   },
  6567.  
  6568.   // Get a compulsory property from a resource. Reports an error if the
  6569.   // property was not present.
  6570.   _getPropertyFromResource: function(aDataSource, aSourceResource, aProperty, aLocalItem) {
  6571.     var rv;
  6572.     try {
  6573.       var property = gRDF.GetResource(EM_NS(aProperty));
  6574.       rv = stringData(aDataSource.GetTarget(aSourceResource, property, true));
  6575.       if (rv === undefined)
  6576.         throw Cr.NS_ERROR_FAILURE;
  6577.     }
  6578.     catch (e) {
  6579.       // XXXben show console message "aProperty" not found on aSourceResource.
  6580.       return null;
  6581.     }
  6582.     return rv;
  6583.   },
  6584.  
  6585.   /**
  6586.    * Parses the Firefox 1.0RC1+ update manifest format looking for new versions
  6587.    * of updated compatibility information about the given add-on.
  6588.    * @param   aDataSource
  6589.    *          The update manifest's datasource
  6590.    * @param   aLocalItem
  6591.    *          The nsIUpdateItem representing the add-on being checked for updates.
  6592.    * @param   aUpdateCheckType
  6593.    *          The type of update check being performed. See the constants in
  6594.    *          nsIExtensionManager
  6595.    * @returns An nsIUpdateItem holding the update's information if a valid
  6596.    *          update is found or null if not.
  6597.    */
  6598.   _parseV20UpdateInfo: function(aDataSource, aLocalItem, aUpdateCheckType) {
  6599.     var extensionRes  = gRDF.GetResource(getItemPrefix(aLocalItem.type) + aLocalItem.id);
  6600.  
  6601.     var updatesArc = gRDF.GetResource(EM_NS("updates"));
  6602.     var updates = aDataSource.GetTarget(extensionRes, updatesArc, true);
  6603.  
  6604.     try {
  6605.       updates = updates.QueryInterface(Ci.nsIRDFResource);
  6606.     }
  6607.     catch (e) {
  6608.       LOG("RDFItemUpdater:_parseV20UpdateInfo: No updates were found for:\r\n" +
  6609.           aLocalItem.id + "\r\n" +
  6610.           "If you are an Extension developer and were expecting there to be\r\n" +
  6611.           "updates, this could mean any number of things, since the RDF system\r\n" +
  6612.           "doesn't give up much in the way of information when the load fails.\r\n" +
  6613.           "\r\nTry checking that: \r\n" +
  6614.           " 1. Your RDF File is correct - e.g. check that there is a top level\r\n" +
  6615.           "    RDF Resource with a URI urn:mozilla:extension:{GUID}, and that\r\n" +
  6616.           "    the <em:updates> listed all have matching GUIDs.");
  6617.       return null;
  6618.     }
  6619.  
  6620.     // Track the newest update found
  6621.     var updatedItem = null;
  6622.  
  6623.     var cu = Cc["@mozilla.org/rdf/container-utils;1"].
  6624.              getService(Ci.nsIRDFContainerUtils);
  6625.     if (cu.IsContainer(aDataSource, updates)) {
  6626.       var ctr = getContainer(aDataSource, updates);
  6627.  
  6628.       var versions = ctr.GetElements();
  6629.       while (versions.hasMoreElements()) {
  6630.         // There are two different methodologies for collecting version
  6631.         // information depending on whether or not we've been invoked in
  6632.         // "version updates only" mode or "version+newest" mode.
  6633.         var version = versions.getNext().QueryInterface(Ci.nsIRDFResource);
  6634.         var foundItem = this._parseV20Update(aDataSource, version, aLocalItem,
  6635.                                              updatedItem ? updatedItem.version : aLocalItem.version,
  6636.                                              aUpdateCheckType);
  6637.         if (foundItem) {
  6638.           // When not checking for new versions we can bail out on the first
  6639.           // result.
  6640.           if (aUpdateCheckType)
  6641.             return foundItem;
  6642.           updatedItem = foundItem;
  6643.         }
  6644.       }
  6645.     }
  6646.     return updatedItem;
  6647.   },
  6648.  
  6649.   /**
  6650.    * Parses a single version's update entry looking for the best matching
  6651.    * targetApplication entry.
  6652.    * @param   aDataSource
  6653.    *          The update manifest's datasource
  6654.    * @param   aUpdateResource
  6655.    *          The nsIRDFResource of the update entry.
  6656.    * @param   aLocalItem
  6657.    *          The nsIUpdateItem representing the add-on being checked for updates.
  6658.    * @param   aNewestVersionFound
  6659.    *          When checking for new versions holds the newest version of this
  6660.    *          add-on that we know about. Otherwise holds the current version.
  6661.    * @param   aUpdateCheckType
  6662.    *          The type of update check being performed. See the constants in
  6663.    *          nsIExtensionManager
  6664.    * @returns An nsIUpdateItem holding the update's information if a valid
  6665.    *          update is found or null if not.
  6666.    */
  6667.   _parseV20Update: function(aDataSource, aUpdateResource, aLocalItem, aNewestVersionFound, aUpdateCheckType) {
  6668.     var version = this._getPropertyFromResource(aDataSource, aUpdateResource,
  6669.                                                 "version", aLocalItem);
  6670.     /* If we are looking for new versions then test whether this discovered
  6671.      * version is greater than any previously found update. Otherwise check
  6672.      * if this update is for the same version as we have installed. */
  6673.     var result = gVersionChecker.compare(version, aNewestVersionFound);
  6674.     if (aUpdateCheckType == Ci.nsIExtensionManager.UPDATE_CHECK_NEWVERSION ? result <= 0 : result != 0)
  6675.       return null;
  6676.  
  6677.     var taArc = gRDF.GetResource(EM_NS("targetApplication"));
  6678.     var targetApps = aDataSource.GetTargets(aUpdateResource, taArc, true);
  6679.     
  6680.     // Track the best update we have found so far
  6681.     var newestUpdateItem = null;
  6682.     while (targetApps.hasMoreElements()) {
  6683.       var targetApp = targetApps.getNext().QueryInterface(Ci.nsIRDFResource);
  6684.       var appID = this._getPropertyFromResource(aDataSource, targetApp, "id", aLocalItem);
  6685.       if (appID != gApp.ID && appID != TOOLKIT_ID)
  6686.         continue;
  6687.  
  6688.       var updateLink = this._getPropertyFromResource(aDataSource, targetApp, "updateLink", aLocalItem);
  6689.       var updateHash = this._getPropertyFromResource(aDataSource, targetApp, "updateHash", aLocalItem);
  6690.       if (aUpdateCheckType == Ci.nsIExtensionManager.UPDATE_CHECK_NEWVERSION) {
  6691.         // New version information is useless without a link to get it from
  6692.         if (!updateLink)
  6693.           continue;
  6694.  
  6695.         /* If the update link is non-ssl and we do not have a hash or the hash
  6696.          * is of an insecure nature then we must ignore this update. Bypass
  6697.          * this if not checking update security. Currently we only consider
  6698.          * the sha hashing algorithms as secure. */
  6699.         if (gCheckUpdateSecurity && updateLink.substring(0, 6) != "https:" && 
  6700.             (!updateHash || updateHash.substring(0, 3) != "sha")) {
  6701.           LOG("RDFItemUpdater:_parseV20Update: Update for " + aLocalItem.id +
  6702.               " at " + updateLink + " ignored because it is insecure. updateLink " +
  6703.               " must be a https url or an updateHash must be specified.");
  6704.           continue;
  6705.         }
  6706.       }
  6707.  
  6708.       var updatedItem = makeItem(aLocalItem.id,
  6709.                                  version,
  6710.                                  aLocalItem.installLocationKey,
  6711.                                  this._getPropertyFromResource(aDataSource, targetApp, "minVersion", aLocalItem),
  6712.                                  this._getPropertyFromResource(aDataSource, targetApp, "maxVersion", aLocalItem),
  6713.                                  aLocalItem.name,
  6714.                                  updateLink,
  6715.                                  updateHash,
  6716.                                  "", /* Icon URL */
  6717.                                  "", /* RDF Update URL */
  6718.                                  "", /* Update Key */
  6719.                                  aLocalItem.type,
  6720.                                  appID);
  6721.  
  6722.       if (this._updater._isValidUpdate(aLocalItem, updatedItem)) {
  6723.         if (aUpdateCheckType == Ci.nsIExtensionManager.UPDATE_CHECK_NEWVERSION) {
  6724.           var infourl = this._getPropertyFromResource(aDataSource, targetApp,
  6725.                                                       "updateInfoURL");
  6726.           if (infourl)
  6727.             infourl = EM_L(infourl);
  6728.           this._updater._emDS.setItemProperty(aLocalItem.id,
  6729.                                               EM_R("availableUpdateInfo"),
  6730.                                               infourl);
  6731.         }
  6732.         if (appID == gApp.ID) {
  6733.           // App takes precedence over toolkit.  If we found the app, bail out.
  6734.           return updatedItem;
  6735.         }
  6736.         newestUpdateItem = updatedItem;
  6737.       }
  6738.     }
  6739.     return newestUpdateItem;
  6740.   }
  6741. };
  6742.  
  6743. /**
  6744.  * A serialisation method for RDF data that produces an identical string
  6745.  * provided that the RDF assertions match.
  6746.  * The serialisation is not complete, only assertions stemming from a given
  6747.  * resource are included, multiple references to the same resource are not
  6748.  * permitted, and the RDF prolog and epilog are not included.
  6749.  * RDF Blob and Date literals are not supported.
  6750.  */
  6751. function RDFSerializer()
  6752. {
  6753.   this.cUtils = Cc["@mozilla.org/rdf/container-utils;1"].
  6754.                 getService(Ci.nsIRDFContainerUtils);
  6755.   this.resources = [];
  6756. }
  6757.  
  6758. RDFSerializer.prototype = {
  6759.   INDENT: "  ",      // The indent used for pretty-printing
  6760.   resources: null,   // Array of the resources that have been found
  6761.   
  6762.   /**
  6763.    * Escapes characters from a string that should not appear in XML.
  6764.    * @param string     The string to be escaped
  6765.    * @returns a string with all characters invalid in XML character data
  6766.    *          converted to entity references.
  6767.    */
  6768.   escapeEntities: function(string)
  6769.   {
  6770.     string = string.replace(/&/g, "&");
  6771.     string = string.replace(/</g, "<");
  6772.     string = string.replace(/>/g, ">");
  6773.     string = string.replace(/"/g, """);
  6774.     return string;
  6775.   },
  6776.   
  6777.   /**
  6778.    * Serializes all the elements of an RDF container.
  6779.    * @param ds         The datasource holding the data
  6780.    * @param container  The RDF container to output the child elements of
  6781.    * @param indent     The current level of indent for pretty-printing
  6782.    * @returns a string containing the serialized elements.
  6783.    */
  6784.   serializeContainerItems: function(ds, container, indent)
  6785.   {
  6786.     var result = "";
  6787.     var items = container.GetElements();
  6788.     while (items.hasMoreElements()) {
  6789.       var item = items.getNext().QueryInterface(Ci.nsIRDFResource);
  6790.       result += indent + "<RDF:li>\n"
  6791.       result += this.serializeResource(ds, item, indent + this.INDENT);
  6792.       result += indent + "</RDF:li>\n"
  6793.     }
  6794.     return result;
  6795.   },
  6796.   
  6797.   /**
  6798.    * Serializes all em:* (see EM_NS) properties of an RDF resource except for
  6799.    * the em:signature property. As this serialization is to be compared against
  6800.    * the manifest signature it cannot contain the em:signature property itself.
  6801.    * @param ds         The datasource holding the data
  6802.    * @param resource   The RDF resource to output the properties of
  6803.    * @param indent     The current level of indent for pretty-printing
  6804.    * @returns a string containing the serialized properties.
  6805.    */
  6806.   serializeResourceProperties: function(ds, resource, indent)
  6807.   {
  6808.     var result = "";
  6809.     var items = [];
  6810.     var arcs = ds.ArcLabelsOut(resource);
  6811.     while (arcs.hasMoreElements()) {
  6812.       var arc = arcs.getNext().QueryInterface(Ci.nsIRDFResource);
  6813.       if (arc.ValueUTF8.substring(0, PREFIX_NS_EM.length) != PREFIX_NS_EM)
  6814.         continue;
  6815.       var prop = arc.ValueUTF8.substring(PREFIX_NS_EM.length);
  6816.       if (prop == "signature")
  6817.         continue;
  6818.   
  6819.       var targets = ds.GetTargets(resource, arc, true);
  6820.       while (targets.hasMoreElements()) {
  6821.         var target = targets.getNext();
  6822.         if (target instanceof Ci.nsIRDFResource) {
  6823.           var item = indent + "<em:" + prop + ">\n";
  6824.           item += this.serializeResource(ds, target, indent + this.INDENT);
  6825.           item += indent + "</em:" + prop + ">\n";
  6826.           items.push(item);
  6827.         }
  6828.         else if (target instanceof Ci.nsIRDFLiteral) {
  6829.           items.push(indent + "<em:" + prop + ">" + this.escapeEntities(target.Value) + "</em:" + prop + ">\n");
  6830.         }
  6831.         else if (target instanceof Ci.nsIRDFInt) {
  6832.           items.push(indent + "<em:" + prop + " NC:parseType=\"Integer\">" + target.Value + "</em:" + prop + ">\n");
  6833.         }
  6834.         else {
  6835.           throw new Error("Cannot serialize unknown literal type");
  6836.         }
  6837.       }
  6838.     }
  6839.     items.sort();
  6840.     result += items.join("");
  6841.     return result;
  6842.   },
  6843.   
  6844.   /**
  6845.    * Recursively serializes an RDF resource and all resources it links to.
  6846.    * This will only output EM_NS properties and will ignore any em:signature
  6847.    * property.
  6848.    * @param ds         The datasource holding the data
  6849.    * @param resource   The RDF resource to serialize
  6850.    * @param indent     The current level of indent for pretty-printing.
  6851.    *                   Leave undefined for no indent
  6852.    * @returns a string containing the serialized resource.
  6853.    * @throws if the RDF data contains multiple references to the same resource.
  6854.    */
  6855.   serializeResource: function(ds, resource, indent)
  6856.   {
  6857.     if (this.resources.indexOf(resource) != -1 ) {
  6858.       // We cannot output multiple references to the same resource.
  6859.       throw new Error("Cannot serialize multiple references to "+resource.Value);
  6860.     }
  6861.     if (indent === undefined)
  6862.       indent = "";
  6863.     
  6864.     this.resources.push(resource);
  6865.     var container = null;
  6866.     var type = "Description";
  6867.     if (this.cUtils.IsSeq(ds, resource)) {
  6868.       type = "Seq";
  6869.       container = this.cUtils.MakeSeq(ds, resource);
  6870.     }
  6871.     else if (this.cUtils.IsAlt(ds, resource)) {
  6872.       type = "Alt";
  6873.       container = this.cUtils.MakeAlt(ds, resource);
  6874.     }
  6875.     else if (this.cUtils.IsBag(ds, resource)) {
  6876.       type = "Bag";
  6877.       container = this.cUtils.MakeBag(ds, resource);
  6878.     }
  6879.   
  6880.     var result = indent + "<RDF:" + type;
  6881.     if (!gRDF.IsAnonymousResource(resource))
  6882.       result += " about=\"" + this.escapeEntities(resource.ValueUTF8) + "\"";
  6883.     result += ">\n";
  6884.   
  6885.     if (container)
  6886.       result += this.serializeContainerItems(ds, container, indent + this.INDENT);
  6887.       
  6888.     result += this.serializeResourceProperties(ds, resource, indent + this.INDENT);
  6889.   
  6890.     result += indent + "</RDF:" + type + ">\n";
  6891.     return result;
  6892.   }
  6893. }
  6894.  
  6895. /**
  6896.  * A Datasource that holds Extensions.
  6897.  * - Implements nsIRDFDataSource to drive UI
  6898.  * - Uses a RDF/XML datasource for storage (this is undesirable)
  6899.  *
  6900.  * @constructor
  6901.  */
  6902. function ExtensionsDataSource(em) {
  6903.   this._em = em;
  6904.  
  6905.   this._itemRoot = gRDF.GetResource(RDFURI_ITEM_ROOT);
  6906.   this._defaultTheme = gRDF.GetResource(RDFURI_DEFAULT_THEME);
  6907. }
  6908. ExtensionsDataSource.prototype = {
  6909.   _inner    : null,
  6910.   _em       : null,
  6911.   _itemRoot     : null,
  6912.   _defaultTheme : null,
  6913.  
  6914.   /**
  6915.    * Determines if an item's dependencies are satisfied. An item's dependencies
  6916.    * are satisifed when all items specified in the item's em:requires arc are
  6917.    * installed, enabled, and the version is compatible based on the em:requires
  6918.    * minVersion and maxVersion.
  6919.    * @param   id
  6920.    *          The ID of the item
  6921.    * @returns true if the item's dependencies are satisfied.
  6922.    *          false if the item's dependencies are not satisfied.
  6923.    */
  6924.   satisfiesDependencies: function(id) {
  6925.     var ds = this._inner;
  6926.     var itemResource = getResourceForID(id);
  6927.     var targets = ds.GetTargets(itemResource, EM_R("requires"), true);
  6928.     if (!targets.hasMoreElements())
  6929.       return true;
  6930.  
  6931.     getVersionChecker();
  6932.     var idRes = EM_R("id");
  6933.     var minVersionRes = EM_R("minVersion");
  6934.     var maxVersionRes = EM_R("maxVersion");
  6935.     while (targets.hasMoreElements()) {
  6936.       var target = targets.getNext().QueryInterface(Ci.nsIRDFResource);
  6937.       var dependencyID = stringData(ds.GetTarget(target, idRes, true));
  6938.       var version = null;
  6939.       version = this.getItemProperty(dependencyID, "version");
  6940.       if (version) {
  6941.         var opType = this.getItemProperty(dependencyID, "opType");
  6942.         if (opType ==  OP_NEEDS_DISABLE || opType == OP_NEEDS_UNINSTALL)
  6943.           return false;
  6944.  
  6945.         if (this.getItemProperty(dependencyID, "userDisabled") == "true" ||
  6946.             this.getItemProperty(dependencyID, "appDisabled") == "true" ||
  6947.             this.getItemProperty(dependencyID, "userDisabled") == OP_NEEDS_DISABLE ||
  6948.             this.getItemProperty(dependencyID, "appDisabled") == OP_NEEDS_DISABLE)
  6949.           return false;
  6950.  
  6951.         var minVersion = stringData(ds.GetTarget(target, minVersionRes, true));
  6952.         var maxVersion = stringData(ds.GetTarget(target, maxVersionRes, true));
  6953.         var compatible = (gVersionChecker.compare(version, minVersion) >= 0 &&
  6954.                           gVersionChecker.compare(version, maxVersion) <= 0);
  6955.         if (!compatible)
  6956.           return false;
  6957.       }
  6958.       else {
  6959.         return false;
  6960.       }
  6961.     }
  6962.  
  6963.     return true;
  6964.   },
  6965.  
  6966.   /**
  6967.    * Determine if an item is compatible
  6968.    * @param   datasource
  6969.    *          The datasource to inspect for compatibility - can be the main
  6970.    *          datasource or an Install Manifest.
  6971.    * @param   source
  6972.    *          The RDF Resource of the item to inspect for compatibility.
  6973.    * @param   appVersion
  6974.    *          The version of the application we are checking for compatibility
  6975.    *          against. If this parameter is undefined, the version of the running
  6976.    *          application is used.
  6977.    * @param   platformVersion
  6978.    *          The version of the toolkit to check compatibility against
  6979.    * @returns true if the item is compatible with this version of the
  6980.    *          application, false, otherwise.
  6981.    */
  6982.   isCompatible: function (datasource, source, appVersion, platformVersion) {
  6983.     // The Default Theme is always compatible.
  6984.     if (source.EqualsNode(this._defaultTheme))
  6985.       return true;
  6986.  
  6987.     var appID = gApp.ID;
  6988.     if (appVersion === undefined)
  6989.       appVersion = gApp.version;
  6990.     if (platformVersion === undefined)
  6991.       var platformVersion = gApp.platformVersion;
  6992.  
  6993.     var targets = datasource.GetTargets(source, EM_R("targetApplication"), true);
  6994.     var idRes = EM_R("id");
  6995.     var minVersionRes = EM_R("minVersion");
  6996.     var maxVersionRes = EM_R("maxVersion");
  6997.     var versionChecker = getVersionChecker();
  6998.     var rv = false;
  6999.     while (targets.hasMoreElements()) {
  7000.       var targetApp = targets.getNext().QueryInterface(Ci.nsIRDFResource);
  7001.       var id          = stringData(datasource.GetTarget(targetApp, idRes, true));
  7002.       var minVersion  = stringData(datasource.GetTarget(targetApp, minVersionRes, true));
  7003.       var maxVersion  = stringData(datasource.GetTarget(targetApp, maxVersionRes, true));
  7004.       if (id == appID) {
  7005.         rv = (versionChecker.compare(appVersion, minVersion) >= 0) &&
  7006.              (versionChecker.compare(appVersion, maxVersion) <= 0);
  7007.         return rv; // App takes precedence over toolkit.
  7008.       }
  7009.  
  7010.       if (id == TOOLKIT_ID) {
  7011.         rv =  (versionChecker.compare(platformVersion, minVersion) >= 0) &&
  7012.               (versionChecker.compare(platformVersion, maxVersion) <= 0);
  7013.         // Keep looping, in case the app id is later.
  7014.       }
  7015.     }
  7016.     return rv;
  7017.   },
  7018.  
  7019.   /**
  7020.    * Gets a list of items that are incompatible with a specific application version.
  7021.    * @param   appID
  7022.    *          The ID of the application - XXXben unused?
  7023.    * @param   appVersion
  7024.    *          The Version of the application to check for incompatibility against.
  7025.    * @param   platformVersion
  7026.    *          The version of the toolkit to check compatibility against
  7027.    * @param   desiredType
  7028.    *          The nsIUpdateItem type of items to look for
  7029.    * @param   includeDisabled
  7030.    *          Whether or not disabled items should be included in the set returned
  7031.    * @returns An array of nsIUpdateItems that are incompatible with the application
  7032.    *          ID/Version supplied.
  7033.    */
  7034.   getIncompatibleItemList: function(appID, appVersion, platformVersion,
  7035.                                     desiredType, includeDisabled) {
  7036.     var items = [];
  7037.     var ctr = getContainer(this._inner, this._itemRoot);
  7038.     var elements = ctr.GetElements();
  7039.     while (elements.hasMoreElements()) {
  7040.       var item = elements.getNext().QueryInterface(Ci.nsIRDFResource);
  7041.       var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  7042.       var type = this.getItemProperty(id, "type");
  7043.       // Skip this item if we're not seeking disabled items
  7044.       if (!includeDisabled && this.getItemProperty(id, "isDisabled") == "true")
  7045.         continue;
  7046.  
  7047.       // If the id of this item matches one of the items potentially installed
  7048.       // with and maintained by this application AND it is installed in the
  7049.       // global install location (i.e. the place installed by the app installer)
  7050.       // it is and can be managed by the update file - it's not an item that has
  7051.       // been manually installed by the user into their profile dir, and as such
  7052.       // it is always compatible with the next release of the application since
  7053.       // we will continue to support it.
  7054.       var locationKey = this.getItemProperty(id, "installLocation");
  7055.       var appManaged = this.getItemProperty(id, "appManaged") == "true";
  7056.       if (appManaged && locationKey == KEY_APP_GLOBAL)
  7057.         continue;
  7058.  
  7059.       if (type != -1 && (type & desiredType) &&
  7060.           !this.isCompatible(this, item, appVersion, platformVersion))
  7061.         items.push(this.getItemForID(id));
  7062.     }
  7063.     return items;
  7064.   },
  7065.  
  7066.   /**
  7067.    * Retrieves a list of items that will be blocklisted by the application for
  7068.    * a specific application or toolkit version.
  7069.    * @param   appVersion
  7070.    *          The Version of the application to check the blocklist against.
  7071.    * @param   platformVersion
  7072.    *          The Version of the toolkit to check the blocklist against.
  7073.    * @param   desiredType
  7074.    *          The nsIUpdateItem type of items to look for
  7075.    * @param   includeAppDisabled
  7076.    *          Whether or not items that are or are already set to be disabled
  7077.    *          by the app on next restart should be included in the set returned
  7078.    * @returns An array of nsIUpdateItems that are blocklisted with the application
  7079.    *          or toolkit version supplied.
  7080.    */
  7081.   getBlocklistedItemList: function(appVersion, platformVersion, desiredType,
  7082.                                    includeAppDisabled) {
  7083.     if (!gBlocklist)
  7084.       gBlocklist = Cc["@mozilla.org/extensions/blocklist;1"].
  7085.                    getService(Ci.nsIBlocklistService);
  7086.     var items = [];
  7087.     var ctr = getContainer(this._inner, this._itemRoot);
  7088.     var elements = ctr.GetElements();
  7089.     while (elements.hasMoreElements()) {
  7090.       var item = elements.getNext().QueryInterface(Ci.nsIRDFResource);
  7091.       var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  7092.       var type = this.getItemProperty(id, "type");
  7093.  
  7094.       if (!includeAppDisabled &&
  7095.           (this.getItemProperty(id, "appDisabled") == "true" ||
  7096.           this.getItemProperty(id, "appDisabled") == OP_NEEDS_DISABLE))
  7097.         continue;
  7098.  
  7099.       var version = this.getItemProperty(id, "version");
  7100.       if (type != -1 && (type & desiredType) &&
  7101.           gBlocklist.isAddonBlocklisted(id, version, appVersion, platformVersion))
  7102.         items.push(this.getItemForID(id));
  7103.     }
  7104.     return items;
  7105.   },
  7106.  
  7107.   /**
  7108.    * Gets a list of items of a specific type
  7109.    * @param   desiredType
  7110.    *          The nsIUpdateItem type of items to return
  7111.    * @param   countRef
  7112.    *          The XPCJS reference to the size of the returned array
  7113.    * @returns An array of nsIUpdateItems, populated only with an item for |id|
  7114.    *          if |id| is non-null, otherwise all items matching the specified
  7115.    *          type.
  7116.    */
  7117.   getItemList: function(desiredType, countRef) {
  7118.     var items = [];
  7119.     var ctr = getContainer(this, this._itemRoot);
  7120.     var elements = ctr.GetElements();
  7121.     while (elements.hasMoreElements()) {
  7122.       var e = elements.getNext().QueryInterface(Ci.nsIRDFResource);
  7123.       var eID = stripPrefix(e.Value, PREFIX_ITEM_URI);
  7124.       var type = this.getItemProperty(eID, "type");
  7125.       if (type != -1 && type & desiredType)
  7126.         items.push(this.getItemForID(eID));
  7127.     }
  7128.     countRef.value = items.length;
  7129.     return items;
  7130.   },
  7131.  
  7132.   /**
  7133.    * Retrieves a list of installed nsIUpdateItems of items that are dependent
  7134.    * on another item.
  7135.    * @param   id
  7136.    *          The ID of the item that other items depend on.
  7137.    * @param   includeDisabled
  7138.    *          Whether to include disabled items in the set returned.
  7139.    * @param   countRef
  7140.    *          The XPCJS reference to the number of items returned.
  7141.    * @returns An array of installed nsIUpdateItems that depend on the item
  7142.    *          specified by the id parameter.
  7143.    */
  7144.   getDependentItemListForID: function(id, includeDisabled, countRef) {
  7145.     var items = [];
  7146.     var ds = this._inner;
  7147.     var ctr = getContainer(this, this._itemRoot);
  7148.     var elements = ctr.GetElements();
  7149.     while (elements.hasMoreElements()) {
  7150.       var e = elements.getNext().QueryInterface(Ci.nsIRDFResource);
  7151.       var dependentID = stripPrefix(e.Value, PREFIX_ITEM_URI);
  7152.       var targets = ds.GetTargets(e, EM_R("requires"), true);
  7153.       var idRes = EM_R("id");
  7154.       while (targets.hasMoreElements()) {
  7155.         var target = targets.getNext().QueryInterface(Ci.nsIRDFResource);
  7156.         var dependencyID = stringData(ds.GetTarget(target, idRes, true));
  7157.         if (dependencyID == id) {
  7158.           if (!includeDisabled && this.getItemProperty(dependentID, "isDisabled") == "true")
  7159.             continue;
  7160.           items.push(this.getItemForID(dependentID));
  7161.           break;
  7162.         }
  7163.       }
  7164.     }
  7165.     countRef.value = items.length;
  7166.     return items;
  7167.   },
  7168.  
  7169.   /**
  7170.    * Constructs an nsIUpdateItem for the given item ID
  7171.    * @param   id
  7172.    *          The GUID of the item to construct a nsIUpdateItem for
  7173.    * @returns The nsIUpdateItem for the id.
  7174.    */
  7175.   getItemForID: function(id) {
  7176.     if (!this.visibleItems[id])
  7177.       return null;
  7178.  
  7179.     var r = getResourceForID(id);
  7180.     if (!r)
  7181.       return null;
  7182.  
  7183.     var targetAppInfo = this.getTargetApplicationInfo(id, this);
  7184.     var updateHash = this.getItemProperty(id, "availableUpdateHash");
  7185.     return makeItem(id,
  7186.                     this.getItemProperty(id, "version"),
  7187.                     this.getItemProperty(id, "installLocation"),
  7188.                     targetAppInfo ? targetAppInfo.minVersion : "",
  7189.                     targetAppInfo ? targetAppInfo.maxVersion : "",
  7190.                     this.getItemProperty(id, "name"),
  7191.                     this.getItemProperty(id, "availableUpdateURL"),
  7192.                     updateHash ? updateHash : "",
  7193.                     this.getItemProperty(id, "iconURL"),
  7194.                     this.getItemProperty(id, "updateURL"),
  7195.                     this.getItemProperty(id, "updateKey"),
  7196.                     this.getItemProperty(id, "type"),
  7197.                     targetAppInfo ? targetAppInfo.appID : gApp.ID);
  7198.   },
  7199.  
  7200.   /**
  7201.    * Gets the name of the Install Location where an item is installed.
  7202.    * @param   id
  7203.    *          The GUID of the item to locate an Install Location for
  7204.    * @returns The string name of the Install Location where the item is
  7205.    *          installed.
  7206.    */
  7207.   getInstallLocationKey: function(id) {
  7208.     return this.getItemProperty(id, "installLocation");
  7209.   },
  7210.  
  7211.   /**
  7212.    * Sets an RDF property on an item in a datasource. Does not create
  7213.    * multiple assertions
  7214.    * @param   datasource
  7215.    *          The target datasource where the property should be set
  7216.    * @param   source
  7217.    *          The RDF Resource to set the property on
  7218.    * @param   property
  7219.    *          The RDF Resource of the property to set
  7220.    * @param   newValue
  7221.    *          The RDF Node containing the new property value
  7222.    */
  7223.   _setProperty: function(datasource, source, property, newValue) {
  7224.     var oldValue = datasource.GetTarget(source, property, true);
  7225.     if (oldValue) {
  7226.       if (newValue)
  7227.         datasource.Change(source, property, oldValue, newValue);
  7228.       else
  7229.         datasource.Unassert(source, property, oldValue);
  7230.     }
  7231.     else if (newValue)
  7232.       datasource.Assert(source, property, newValue, true);
  7233.   },
  7234.  
  7235.   /**
  7236.    * Gets the updated target application info if it exists for an item from
  7237.    * the Extensions datasource during an installation or upgrade.
  7238.    * @param   id
  7239.    *          The ID of the item to discover updated target application info for
  7240.    * @returns A JS Object with the following properties:
  7241.    *          "id"            The id of the item
  7242.    *          "minVersion"    The updated minimum version of the target
  7243.    *                          application that this item can run in
  7244.    *          "maxVersion"    The updated maximum version of the target
  7245.    *                          application that this item can run in
  7246.    */
  7247.   getUpdatedTargetAppInfo: function(id) {
  7248.     // The default theme is always compatible so there is never update info.
  7249.     if (getResourceForID(id).EqualsNode(this._defaultTheme))
  7250.       return null;
  7251.  
  7252.     var appID = gApp.ID;
  7253.     var r = getResourceForID(id);
  7254.     var targetApps = this._inner.GetTargets(r, EM_R("targetApplication"), true);
  7255.     if (!targetApps.hasMoreElements())
  7256.       targetApps = this._inner.GetTargets(gInstallManifestRoot, EM_R("targetApplication"), true);
  7257.     var outData = null;
  7258.     while (targetApps.hasMoreElements()) {
  7259.       var targetApp = targetApps.getNext();
  7260.       if (targetApp instanceof Ci.nsIRDFResource) {
  7261.         try {
  7262.           var foundAppID = stringData(this._inner.GetTarget(targetApp, EM_R("id"), true));
  7263.           // Different target application?
  7264.           if (foundAppID != appID && foundAppID != TOOLKIT_ID)
  7265.             continue;
  7266.           var updatedMinVersion = this._inner.GetTarget(targetApp, EM_R("updatedMinVersion"), true);
  7267.           var updatedMaxVersion = this._inner.GetTarget(targetApp, EM_R("updatedMaxVersion"), true);
  7268.           if (updatedMinVersion && updatedMaxVersion)
  7269.             outData = { id          : id,
  7270.                         targetAppID : foundAppID,
  7271.                         minVersion  : stringData(updatedMinVersion),
  7272.                         maxVersion  : stringData(updatedMaxVersion) };
  7273.           if (foundAppID == appID)
  7274.             return outData;
  7275.         }
  7276.         catch (e) {
  7277.           continue;
  7278.         }
  7279.       }
  7280.     }
  7281.     return outData;
  7282.   },
  7283.  
  7284.   /**
  7285.    * Sets the updated target application info for an item in the Extensions
  7286.    * datasource during an installation or upgrade.
  7287.    * @param   id
  7288.    *          The ID of the item to set updated target application info for
  7289.    * @param   targetAppID
  7290.    *          The target application ID used for checking compatibility for this item.
  7291.    * @param   updatedMinVersion
  7292.    *          The updated minimum version of the target application that this
  7293.    *          item can run in
  7294.    * @param   updatedMaxVersion
  7295.    *          The updated maximum version of the target application that this
  7296.    *          item can run in
  7297.    *
  7298.    * @note Add-ons can specify a targetApplication id of toolkit@mozilla.org in
  7299.    *       their install manifest for compatibility with all apps using a
  7300.    *       specific release of the toolkit.
  7301.    */
  7302.   setUpdatedTargetAppInfo: function(id, targetAppID, updatedMinVersion, updatedMaxVersion) {
  7303.     // The default theme is always compatible so it is never updated.
  7304.     if (getResourceForID(id).EqualsNode(this._defaultTheme))
  7305.       return;
  7306.  
  7307.     // Version/Dependency Info
  7308.     var updatedMinVersionRes = EM_R("updatedMinVersion");
  7309.     var updatedMaxVersionRes = EM_R("updatedMaxVersion");
  7310.  
  7311.     var appID = gApp.ID;
  7312.     var r = getResourceForID(id);
  7313.     var targetApps = this._inner.GetTargets(r, EM_R("targetApplication"), true);
  7314.     // add updatedMinVersion and updatedMaxVersion for an install else an upgrade
  7315.     if (!targetApps.hasMoreElements()) {
  7316.       var idRes = EM_R("id");
  7317.       var targetRes = getResourceForID(id);
  7318.       var property = EM_R("targetApplication");
  7319.       var anon = gRDF.GetAnonymousResource();
  7320.       this._inner.Assert(anon, idRes, EM_L(appID), true);
  7321.       this._inner.Assert(anon, updatedMinVersionRes, EM_L(updatedMinVersion), true);
  7322.       this._inner.Assert(anon, updatedMaxVersionRes, EM_L(updatedMaxVersion), true);
  7323.       this._inner.Assert(targetRes, property, anon, true);
  7324.     }
  7325.     else {
  7326.       while (targetApps.hasMoreElements()) {
  7327.         var targetApp = targetApps.getNext();
  7328.         if (targetApp instanceof Ci.nsIRDFResource) {
  7329.           var foundAppID = stringData(this._inner.GetTarget(targetApp, EM_R("id"), true));
  7330.           // Different target application?
  7331.           if (foundAppID != targetAppID)
  7332.             continue;
  7333.           this._inner.Assert(targetApp, updatedMinVersionRes, EM_L(updatedMinVersion), true);
  7334.           this._inner.Assert(targetApp, updatedMaxVersionRes, EM_L(updatedMaxVersion), true);
  7335.           break;
  7336.         }
  7337.       }
  7338.     }
  7339.     this.Flush();
  7340.   },
  7341.  
  7342.   /**
  7343.    * Gets the target application info for an item from a datasource.
  7344.    * @param   id
  7345.    *          The GUID of the item to discover target application info for
  7346.    * @param   datasource
  7347.    *          The datasource to look up target application info in
  7348.    * @returns A JS Object with the following properties:
  7349.    *          "appID"         The target application ID used for checking
  7350.    *                          compatibility for this item.
  7351.    *          "minVersion"    The minimum version of the target application
  7352.    *                          that this item can run in
  7353.    *          "maxVersion"    The maximum version of the target application
  7354.    *                          that this item can run in
  7355.    *          or null, if no target application data exists for the specified
  7356.    *          id in the supplied datasource.
  7357.    */
  7358.   getTargetApplicationInfo: function(id, datasource) {
  7359.     var appID = gApp.ID;
  7360.     // The default theme is always compatible.
  7361.     if (getResourceForID(id).EqualsNode(this._defaultTheme)) {
  7362.       var ver = gApp.version;
  7363.       return { appID: appID, minVersion: ver, maxVersion: ver };
  7364.     }
  7365.  
  7366.     var r = getResourceForID(id);
  7367.     var targetApps = datasource.GetTargets(r, EM_R("targetApplication"), true);
  7368.     if (!targetApps)
  7369.       return null;
  7370.  
  7371.     if (!targetApps.hasMoreElements())
  7372.       targetApps = datasource.GetTargets(gInstallManifestRoot, EM_R("targetApplication"), true);
  7373.     var outData = null;
  7374.     while (targetApps.hasMoreElements()) {
  7375.       var targetApp = targetApps.getNext();
  7376.       if (targetApp instanceof Ci.nsIRDFResource) {
  7377.         try {
  7378.           var foundAppID = stringData(datasource.GetTarget(targetApp, EM_R("id"), true));
  7379.           // Different target application?
  7380.           if (foundAppID != appID && foundAppID != TOOLKIT_ID)
  7381.             continue;
  7382.  
  7383.           outData = { appID: foundAppID,
  7384.                       minVersion: stringData(datasource.GetTarget(targetApp, EM_R("minVersion"), true)),
  7385.                       maxVersion: stringData(datasource.GetTarget(targetApp, EM_R("maxVersion"), true)) };
  7386.           if (foundAppID == appID)
  7387.             return outData;
  7388.         }
  7389.         catch (e) {
  7390.           continue;
  7391.         }
  7392.       }
  7393.     }
  7394.     return outData;
  7395.   },
  7396.  
  7397.   /**
  7398.    * Sets the target application info for an item in a datasource.
  7399.    * @param   id
  7400.    *          The GUID of the item to discover target application info for
  7401.    * @param   targetAppID
  7402.    *          The target application ID used for checking compatibility for this
  7403.    *          item.
  7404.    * @param   minVersion
  7405.    *          The minimum version of the target application that this item can
  7406.    *          run in
  7407.    * @param   maxVersion
  7408.    *          The maximum version of the target application that this item can
  7409.    *          run in
  7410.    * @param   datasource
  7411.    *          The datasource to look up target application info in
  7412.    *
  7413.    * @note Add-ons can specify a targetApplication id of toolkit@mozilla.org in
  7414.    *       their install manifest for compatibility with all apps using a
  7415.    *       specific release of the toolkit.
  7416.    */
  7417.   setTargetApplicationInfo: function(id, targetAppID, minVersion, maxVersion, datasource) {
  7418.     var targetDataSource = datasource;
  7419.     if (!targetDataSource)
  7420.       targetDataSource = this._inner;
  7421.  
  7422.     var appID = gApp.ID;
  7423.     var r = getResourceForID(id);
  7424.     var targetApps = targetDataSource.GetTargets(r, EM_R("targetApplication"), true);
  7425.     if (!targetApps.hasMoreElements())
  7426.       targetApps = datasource.GetTargets(gInstallManifestRoot, EM_R("targetApplication"), true);
  7427.     while (targetApps.hasMoreElements()) {
  7428.       var targetApp = targetApps.getNext();
  7429.       if (targetApp instanceof Ci.nsIRDFResource) {
  7430.         var foundAppID = stringData(targetDataSource.GetTarget(targetApp, EM_R("id"), true));
  7431.         // Different target application?
  7432.         if (foundAppID != targetAppID)
  7433.           continue;
  7434.  
  7435.         this._setProperty(targetDataSource, targetApp, EM_R("minVersion"), EM_L(minVersion));
  7436.         this._setProperty(targetDataSource, targetApp, EM_R("maxVersion"), EM_L(maxVersion));
  7437.  
  7438.         // If we were setting these properties on the main datasource, flush
  7439.         // it now. (Don't flush changes set on Install Manifests - they are
  7440.         // fleeting).
  7441.         if (!datasource)
  7442.           this.Flush();
  7443.  
  7444.         break;
  7445.       }
  7446.     }
  7447.   },
  7448.  
  7449.   /**
  7450.    * Gets a property of an item
  7451.    * @param   id
  7452.    *          The GUID of the item
  7453.    * @param   property
  7454.    *          The name of the property (excluding EM_NS)
  7455.    * @returns The literal value of the property, or undefined if there is no
  7456.    *          value.
  7457.    */
  7458.   getItemProperty: function(id, property) {
  7459.     var item = getResourceForID(id);
  7460.     if (!item) {
  7461.       LOG("getItemProperty failing for lack of an item. This means getResourceForItem \
  7462.            failed to locate a resource for aItemID (item ID = " + id + ", property = " + property + ")");
  7463.     }
  7464.     else
  7465.       return this._getItemProperty(item, property);
  7466.     return undefined;
  7467.   },
  7468.  
  7469.   /**
  7470.    * Gets a property of an item resource
  7471.    * @param   itemResource
  7472.    *          The RDF Resource of the item
  7473.    * @param   property
  7474.    *          The name of the property (excluding EM_NS)
  7475.    * @returns The literal value of the property, or undefined if there is no
  7476.    *          value.
  7477.    */
  7478.   _getItemProperty: function(itemResource, property) {
  7479.     var target = this.GetTarget(itemResource, EM_R(property), true);
  7480.     var value = stringData(target);
  7481.     if (value === undefined)
  7482.       value = intData(target);
  7483.     return value === undefined ? "" : value;
  7484.   },
  7485.  
  7486.   /**
  7487.    * Sets a property on an item.
  7488.    * @param   id
  7489.    *          The GUID of the item
  7490.    * @param   propertyArc
  7491.    *          The RDF Resource of the property arc
  7492.    * @param   propertyValue
  7493.    *          A nsIRDFLiteral value of the property to be set
  7494.    */
  7495.   setItemProperty: function (id, propertyArc, propertyValue) {
  7496.     var item = getResourceForID(id);
  7497.     this._setProperty(this._inner, item, propertyArc, propertyValue);
  7498.     this.Flush();
  7499.   },
  7500.  
  7501.   /**
  7502.    * Inserts the RDF resource for an item into a container.
  7503.    * @param   id
  7504.    *          The GUID of the item
  7505.    */
  7506.   insertItemIntoContainer: function(id) {
  7507.     // Get the target container and resource
  7508.     var ctr = getContainer(this._inner, this._itemRoot);
  7509.     var itemResource = getResourceForID(id);
  7510.     // Don't bother adding the extension to the list if it's already there.
  7511.     // (i.e. we're upgrading)
  7512.     var oldIndex = ctr.IndexOf(itemResource);
  7513.     if (oldIndex == -1)
  7514.       ctr.AppendElement(itemResource);
  7515.     this.Flush();
  7516.   },
  7517.  
  7518.   /**
  7519.    * Removes the RDF resource for an item from its container.
  7520.    * @param   id
  7521.    *          The GUID of the item
  7522.    */
  7523.   removeItemFromContainer: function(id) {
  7524.     var ctr = getContainer(this._inner, this._itemRoot);
  7525.     var itemResource = getResourceForID(id);
  7526.     ctr.RemoveElement(itemResource, true);
  7527.     this.Flush();
  7528.   },
  7529.  
  7530.   /**
  7531.    * Removes a corrupt item entry from the extension list added due to buggy
  7532.    * code in previous EM versions!
  7533.    * @param   id
  7534.    *          The GUID of the item
  7535.    */
  7536.   removeCorruptItem: function(id) {
  7537.     this.removeItemMetadata(id);
  7538.     this.removeItemFromContainer(id);
  7539.     this.visibleItems[id] = null;
  7540.   },
  7541.  
  7542.   /**
  7543.    * Removes a corrupt download entry from the list
  7544.    * @param   uri
  7545.    *          The RDF URI of the item.
  7546.    * @returns The RDF Resource of the removed entry
  7547.    */
  7548.   removeCorruptDLItem: function(uri) {
  7549.     var itemResource = gRDF.GetResource(uri);
  7550.     var ctr = getContainer(this._inner, this._itemRoot);
  7551.     if (ctr.IndexOf(itemResource) != -1) {
  7552.       ctr.RemoveElement(itemResource, true);
  7553.       this._cleanResource(itemResource);
  7554.       this.Flush();
  7555.     }
  7556.     return itemResource;
  7557.   },
  7558.  
  7559.   /**
  7560.    * Copies localized properties from an install manifest to the datasource
  7561.    *
  7562.    * @param   installManifest
  7563.    *          The Install Manifest datasource we are copying from
  7564.    * @param   source
  7565.    *          The source resource of the localized properties
  7566.    * @param   target
  7567.    *          The target resource to store the localized properties
  7568.    */
  7569.   _addLocalizedMetadata: function(installManifest, sourceRes, targetRes)
  7570.   {
  7571.     var singleProps = ["name", "description", "creator", "homepageURL"];
  7572.  
  7573.     for (var i = 0; i < singleProps.length; ++i) {
  7574.       var property = EM_R(singleProps[i]);
  7575.       var literal = installManifest.GetTarget(sourceRes, property, true);
  7576.       // If literal is null, _setProperty will remove any existing.
  7577.       this._setProperty(this._inner, targetRes, property, literal);
  7578.     }
  7579.  
  7580.     // Assert properties with multiple values
  7581.     var manyProps = ["developer", "translator", "contributor"];
  7582.     for (var i = 0; i < manyProps.length; ++i) {
  7583.       var property = EM_R(manyProps[i]);
  7584.       var literals = installManifest.GetTargets(sourceRes, property, true);
  7585.  
  7586.       var oldValues = this._inner.GetTargets(targetRes, property, true);
  7587.       while (oldValues.hasMoreElements()) {
  7588.         var oldValue = oldValues.getNext().QueryInterface(Ci.nsIRDFNode);
  7589.         this._inner.Unassert(targetRes, property, oldValue);
  7590.       }
  7591.       while (literals.hasMoreElements()) {
  7592.         var literal = literals.getNext().QueryInterface(Ci.nsIRDFNode);
  7593.         this._inner.Assert(targetRes, property, literal, true);
  7594.       }
  7595.     }
  7596.  
  7597.   },
  7598.  
  7599.   /**
  7600.    * Copies metadata from an Install Manifest Datasource into the Extensions
  7601.    * DataSource.
  7602.    * @param   id
  7603.    *          The GUID of the item
  7604.    * @param   installManifest
  7605.    *          The Install Manifest datasource we are copying from
  7606.    * @param   installLocation
  7607.    *          The Install Location of the item.
  7608.    */
  7609.   addItemMetadata: function(id, installManifest, installLocation) {
  7610.     var targetRes = getResourceForID(id);
  7611.     // Remove any temporary assertions used for the install process
  7612.     this._setProperty(this._inner, targetRes, EM_R("newVersion"), null);
  7613.     // Copy the assertions over from the source datasource.
  7614.     // Assert properties with single values
  7615.     var singleProps = ["version", "updateURL", "updateService", "optionsURL",
  7616.                        "aboutURL", "iconURL", "internalName", "updateKey"];
  7617.  
  7618.     // Items installed into restricted Install Locations can also be locked
  7619.     // (can't be removed or disabled), and hidden (not shown in the UI)
  7620.     if (installLocation.restricted)
  7621.       singleProps = singleProps.concat(["locked", "hidden"]);
  7622.     if (installLocation.name == KEY_APP_GLOBAL)
  7623.       singleProps = singleProps.concat(["appManaged"]);
  7624.     for (var i = 0; i < singleProps.length; ++i) {
  7625.       var property = EM_R(singleProps[i]);
  7626.       var literal = installManifest.GetTarget(gInstallManifestRoot, property, true);
  7627.       // If literal is null, _setProperty will remove any existing.
  7628.       this._setProperty(this._inner, targetRes, property, literal);
  7629.     }
  7630.  
  7631.     var localizedProp = EM_R("localized");
  7632.     var localeProp = EM_R("locale");
  7633.     // Remove old localized properties
  7634.     var oldValues = this._inner.GetTargets(targetRes, localizedProp, true);
  7635.     while (oldValues.hasMoreElements()) {
  7636.       var oldValue = oldValues.getNext().QueryInterface(Ci.nsIRDFNode);
  7637.       this._cleanResource(oldValue);
  7638.       this._inner.Unassert(targetRes, localizedProp, oldValue);
  7639.     }
  7640.     // Add each localized property
  7641.     var localizations = installManifest.GetTargets(gInstallManifestRoot, localizedProp, true);
  7642.     while (localizations.hasMoreElements()) {
  7643.       var localization = localizations.getNext().QueryInterface(Ci.nsIRDFResource);
  7644.       var anon = gRDF.GetAnonymousResource();
  7645.       var literals = installManifest.GetTargets(localization, localeProp, true);
  7646.       while (literals.hasMoreElements()) {
  7647.         var literal = literals.getNext().QueryInterface(Ci.nsIRDFNode);
  7648.         this._inner.Assert(anon, localeProp, literal, true);
  7649.       }
  7650.       this._addLocalizedMetadata(installManifest, localization, anon);
  7651.       this._inner.Assert(targetRes, localizedProp, anon, true);
  7652.     }
  7653.     // Add the fallback properties
  7654.     this._addLocalizedMetadata(installManifest, gInstallManifestRoot, targetRes);
  7655.  
  7656.     // Version/Dependency Info
  7657.     var versionProps = ["targetApplication", "requires"];
  7658.     var idRes = EM_R("id");
  7659.     var minVersionRes = EM_R("minVersion");
  7660.     var maxVersionRes = EM_R("maxVersion");
  7661.     for (var i = 0; i < versionProps.length; ++i) {
  7662.       var property = EM_R(versionProps[i]);
  7663.       var newVersionInfos = installManifest.GetTargets(gInstallManifestRoot, property, true);
  7664.  
  7665.       var oldVersionInfos = this._inner.GetTargets(targetRes, property, true);
  7666.       while (oldVersionInfos.hasMoreElements()) {
  7667.         var oldVersionInfo = oldVersionInfos.getNext().QueryInterface(Ci.nsIRDFResource);
  7668.         this._cleanResource(oldVersionInfo);
  7669.         this._inner.Unassert(targetRes, property, oldVersionInfo);
  7670.       }
  7671.       while (newVersionInfos.hasMoreElements()) {
  7672.         var newVersionInfo = newVersionInfos.getNext().QueryInterface(Ci.nsIRDFResource);
  7673.         var anon = gRDF.GetAnonymousResource();
  7674.         this._inner.Assert(anon, idRes, installManifest.GetTarget(newVersionInfo, idRes, true), true);
  7675.         this._inner.Assert(anon, minVersionRes, installManifest.GetTarget(newVersionInfo, minVersionRes, true), true);
  7676.         this._inner.Assert(anon, maxVersionRes, installManifest.GetTarget(newVersionInfo, maxVersionRes, true), true);
  7677.         this._inner.Assert(targetRes, property, anon, true);
  7678.       }
  7679.     }
  7680.     this.updateProperty(id, "opType");
  7681.     this.updateProperty(id, "updateable");
  7682.     this.Flush();
  7683.   },
  7684.  
  7685.   /**
  7686.    * Strips an item entry of all assertions.
  7687.    * @param   id
  7688.    *          The GUID of the item
  7689.    */
  7690.   removeItemMetadata: function(id) {
  7691.     var item = getResourceForID(id);
  7692.     var resources = ["targetApplication", "requires", "localized"];
  7693.     for (var i = 0; i < resources.length; ++i) {
  7694.       var targetApps = this._inner.GetTargets(item, EM_R(resources[i]), true);
  7695.       while (targetApps.hasMoreElements()) {
  7696.         var targetApp = targetApps.getNext().QueryInterface(Ci.nsIRDFResource);
  7697.         this._cleanResource(targetApp);
  7698.       }
  7699.     }
  7700.  
  7701.     this._cleanResource(item);
  7702.   },
  7703.  
  7704.   /**
  7705.    * Strips a resource of all outbound assertions. We use methods like this
  7706.    * since the RDFXMLDatasource will write out all assertions, even if they
  7707.    * are not connected through our root.
  7708.    * @param   resource
  7709.    *          The resource to clean.
  7710.    */
  7711.   _cleanResource: function(resource) {
  7712.     // Remove outward arcs
  7713.     var arcs = this._inner.ArcLabelsOut(resource);
  7714.     while (arcs.hasMoreElements()) {
  7715.       var arc = arcs.getNext().QueryInterface(Ci.nsIRDFResource);
  7716.       var targets = this._inner.GetTargets(resource, arc, true);
  7717.       while (targets.hasMoreElements()) {
  7718.         var value = targets.getNext().QueryInterface(Ci.nsIRDFNode);
  7719.         if (value)
  7720.           this._inner.Unassert(resource, arc, value);
  7721.       }
  7722.     }
  7723.   },
  7724.  
  7725.   /**
  7726.    * Notify views that this propery has changed (this is for properties that
  7727.    * are implemented by this datasource rather than by the inner in-memory
  7728.    * datasource and thus do not get free change handling).
  7729.    * @param   id
  7730.    *          The GUID of the item to update the property for.
  7731.    * @param   property
  7732.    *          The property (less EM_NS) to update.
  7733.    */
  7734.   updateProperty: function(id, property) {
  7735.     var item = getResourceForID(id);
  7736.     this._updateProperty(item, property);
  7737.   },
  7738.  
  7739.   /**
  7740.    * Notify views that this propery has changed (this is for properties that
  7741.    * are implemented by this datasource rather than by the inner in-memory
  7742.    * datasource and thus do not get free change handling). This allows updating
  7743.    * properties for download items which don't have the em item prefix in there
  7744.    ( resource value. In most instances updateProperty should be used.
  7745.    * @param   item
  7746.    *          The item to update the property for.
  7747.    * @param   property
  7748.    *          The property (less EM_NS) to update.
  7749.    */
  7750.   _updateProperty: function(item, property) {
  7751.     if (item) {
  7752.       var propertyResource = EM_R(property);
  7753.       var value = this.GetTarget(item, propertyResource, true);
  7754.       for (var i = 0; i < this._observers.length; ++i) {
  7755.         if (value)
  7756.           this._observers[i].onChange(this, item, propertyResource,
  7757.                                       EM_L(""), value);
  7758.         else
  7759.           this._observers[i].onUnassert(this, item, propertyResource,
  7760.                                         EM_L(""));
  7761.       }
  7762.     }
  7763.   },
  7764.  
  7765.   /**
  7766.    * Move an Item to the index of another item in its container.
  7767.    * @param   movingID
  7768.    *          The ID of the item to be moved.
  7769.    * @param   destinationID
  7770.    *          The ID of an item to move another item to.
  7771.    */
  7772.   moveToIndexOf: function(movingID, destinationID) {
  7773.     var extensions = gRDF.GetResource(RDFURI_ITEM_ROOT);
  7774.     var ctr = getContainer(this._inner, extensions);
  7775.     var item = gRDF.GetResource(movingID);
  7776.     var index = ctr.IndexOf(gRDF.GetResource(destinationID));
  7777.     if (index == -1)
  7778.       index = 1; // move to the beginning if destinationID is not found
  7779.     this._inner.beginUpdateBatch();
  7780.     ctr.RemoveElement(item, true);
  7781.     ctr.InsertElementAt(item, index, true);
  7782.     this._inner.endUpdateBatch();
  7783.     this.Flush();
  7784.   },
  7785.  
  7786.   /**
  7787.    * Sorts addons of the specified type by the specified property starting from
  7788.    * the top of their container. If the addons are already sorted then no action
  7789.    * is performed.
  7790.    * @param   type
  7791.    *          The nsIUpdateItem type of the items to sort.
  7792.    * @param   propertyName
  7793.    *          The RDF property name used for sorting.
  7794.    * @param   isAscending
  7795.    *          true to sort ascending and false to sort descending
  7796.    */
  7797.   sortTypeByProperty: function(type, propertyName, isAscending) {
  7798.     var items = [];
  7799.     var ctr = getContainer(this._inner, this._itemRoot);
  7800.     var elements = ctr.GetElements();
  7801.     // Base 0 ordinal for checking against the existing order after sorting
  7802.     var ordinal = 0;
  7803.     while (elements.hasMoreElements()) {
  7804.       var item = elements.getNext().QueryInterface(Ci.nsIRDFResource);
  7805.       var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  7806.       var itemType = this.getItemProperty(id, "type");
  7807.       if (itemType & type) {
  7808.         items.push({ item   : item,
  7809.                      ordinal: ordinal,
  7810.                      sortkey: this.getItemProperty(id, propertyName).toLowerCase() });
  7811.         ordinal++;
  7812.       }
  7813.     }
  7814.  
  7815.     var direction = isAscending ? 1 : -1;
  7816.     // Case insensitive sort
  7817.     function compare(a, b) {
  7818.         if (a.sortkey < b.sortkey) return (-1 * direction);
  7819.         if (a.sortkey > b.sortkey) return (1 * direction);
  7820.         return 0;
  7821.     }
  7822.     items.sort(compare);
  7823.  
  7824.     // Check if there are any changes in the order of the items
  7825.     var isDirty = false;
  7826.     for (var i = 0; i < items.length; i++) {
  7827.       if (items[i].ordinal != i) {
  7828.         isDirty = true;
  7829.         break;
  7830.       }
  7831.     }
  7832.  
  7833.     // If there are no changes then early return to avoid the perf impact
  7834.     if (!isDirty)
  7835.       return;
  7836.  
  7837.     // Reorder the items by moving them to the top of the container
  7838.     this.beginUpdateBatch();
  7839.     for (i = 0; i < items.length; i++) {
  7840.       ctr.RemoveElement(items[i].item, true);
  7841.       ctr.InsertElementAt(items[i].item, i + 1, true);
  7842.     }
  7843.     this.endUpdateBatch();
  7844.     this.Flush();
  7845.   },
  7846.  
  7847.   /**
  7848.    * Determines if an Item is an active download
  7849.    * @param   id
  7850.    *          The ID of the item. This will be a uri scheme without the
  7851.    *          em item prefix so getProperty shouldn't be used.
  7852.    * @returns true if the item is an active download, false otherwise.
  7853.    */
  7854.   isDownloadItem: function(id) {
  7855.     var downloadURL = stringData(this.GetTarget(gRDF.GetResource(id), EM_R("downloadURL"), true));
  7856.     return downloadURL && downloadURL != "";
  7857.   },
  7858.  
  7859.   /**
  7860.    * Adds an entry representing an active download to the appropriate container
  7861.    * @param   addon
  7862.    *          An object implementing nsIUpdateItem for the addon being
  7863.    *          downloaded.
  7864.    */
  7865.   addDownload: function(addon) {
  7866.     // Updates have already been added to the datasource so we just update the
  7867.     // download state.
  7868.     if (addon.id != addon.xpiURL) {
  7869.       this.updateDownloadState(PREFIX_ITEM_URI + addon.id, "waiting");
  7870.       return;
  7871.     }
  7872.     var res = gRDF.GetResource(addon.xpiURL);
  7873.     this._setProperty(this._inner, res, EM_R("name"), EM_L(addon.name));
  7874.     this._setProperty(this._inner, res, EM_R("version"), EM_L(addon.version));
  7875.     this._setProperty(this._inner, res, EM_R("iconURL"), EM_L(addon.iconURL));
  7876.     this._setProperty(this._inner, res, EM_R("downloadURL"), EM_L(addon.xpiURL));
  7877.     this._setProperty(this._inner, res, EM_R("type"), EM_I(addon.type));
  7878.  
  7879.     var ctr = getContainer(this._inner, this._itemRoot);
  7880.     if (ctr.IndexOf(res) == -1)
  7881.       ctr.AppendElement(res);
  7882.  
  7883.     this.updateDownloadState(addon.xpiURL, "waiting");
  7884.     this.Flush();
  7885.   },
  7886.  
  7887.   /**
  7888.    * Adds an entry representing an item that is incompatible and is being
  7889.    * checked for a compatibility update.
  7890.    * @param   name
  7891.    *          The display name of the item being checked
  7892.    * @param   url
  7893.    *          The URL string of the xpi file that has been staged.
  7894.    * @param   type
  7895.    *          The nsIUpdateItem type of the item
  7896.    * @param   version
  7897.    *          The version of the item
  7898.    */
  7899.   addIncompatibleUpdateItem: function(name, url, type, version) {
  7900.     var iconURL = (type == Ci.nsIUpdateItem.TYPE_THEME) ? URI_GENERIC_ICON_THEME :
  7901.                                                           URI_GENERIC_ICON_XPINSTALL;
  7902.     var extensionsStrings = BundleManager.getBundle(URI_EXTENSIONS_PROPERTIES);
  7903.     var updateMsg = extensionsStrings.formatStringFromName("incompatibleUpdateMessage",
  7904.                                                            [BundleManager.appName, name], 2)
  7905.  
  7906.     var res = gRDF.GetResource(url);
  7907.     this._setProperty(this._inner, res, EM_R("name"), EM_L(name));
  7908.     this._setProperty(this._inner, res, EM_R("iconURL"), EM_L(iconURL));
  7909.     this._setProperty(this._inner, res, EM_R("downloadURL"), EM_L(url));
  7910.     this._setProperty(this._inner, res, EM_R("type"), EM_I(type));
  7911.     this._setProperty(this._inner, res, EM_R("version"), EM_L(version));
  7912.     this._setProperty(this._inner, res, EM_R("incompatibleUpdate"), EM_L("true"));
  7913.     this._setProperty(this._inner, res, EM_R("description"), EM_L(updateMsg));
  7914.  
  7915.     var ctr = getContainer(this._inner, this._itemRoot);
  7916.     if (ctr.IndexOf(res) == -1)
  7917.       ctr.AppendElement(res);
  7918.  
  7919.     this.updateDownloadState(url, "incompatibleUpdate");
  7920.     this.Flush();
  7921.   },
  7922.  
  7923.   /**
  7924.    * Removes an active download from the appropriate container
  7925.    * @param   url
  7926.    *          The URL string of the active download to be removed
  7927.    */
  7928.   removeDownload: function(url) {
  7929.     var res = gRDF.GetResource(url);
  7930.     var ctr = getContainer(this._inner, this._itemRoot);
  7931.     if (ctr.IndexOf(res) != -1)
  7932.       ctr.RemoveElement(res, true);
  7933.     this._cleanResource(res);
  7934.     this.updateDownloadState(url, null);
  7935.     this.Flush();
  7936.   },
  7937.  
  7938.   /**
  7939.    * A hash of RDF resource values (e.g. Add-on IDs or XPI URLs) that represent
  7940.    * installation progress for a single browser session.
  7941.    */
  7942.   _progressData: { },
  7943.  
  7944.   /**
  7945.    * Updates the install progress data for a given ID (e.g. Add-on IDs or
  7946.    * XPI URLs).
  7947.    * @param   id
  7948.    *          The URL string of the active download to be removed
  7949.    * @param   state
  7950.    *          The current state in the installation process. If null the object
  7951.    *          is deleted from _progressData.
  7952.    */
  7953.   updateDownloadState: function(id, state) {
  7954.     if (!state) {
  7955.       if (id in this._progressData)
  7956.         delete this._progressData[id];
  7957.       return;
  7958.     }
  7959.     else {
  7960.       if (!(id in this._progressData))
  7961.         this._progressData[id] = { };
  7962.       this._progressData[id].state = state;
  7963.     }
  7964.     var item = gRDF.GetResource(id);
  7965.     this._updateProperty(item, "state");
  7966.   },
  7967.  
  7968.   updateDownloadProgress: function(id, progress) {
  7969.     if (!progress) {
  7970.       if (!(id in this._progressData))
  7971.         return;
  7972.       this._progressData[id].progress = null;
  7973.     }
  7974.     else {
  7975.       if (!(id in this._progressData))
  7976.         this.updateDownloadState(id, "downloading");
  7977.  
  7978.       if (this._progressData[id].progress == progress)
  7979.         return;
  7980.  
  7981.       this._progressData[id].progress = progress;
  7982.     }
  7983.     var item = gRDF.GetResource(id);
  7984.     this._updateProperty(item, "progress");
  7985.   },
  7986.  
  7987.   /**
  7988.    * A GUID->location-key hash of items that are visible to the application.
  7989.    * These are items that show up in the Extension/Themes etc UI. If there is
  7990.    * an instance of the same item installed in Install Locations of differing
  7991.    * profiles, the item at the highest priority location will appear in this
  7992.    * list.
  7993.    */
  7994.   visibleItems: { },
  7995.  
  7996.   /**
  7997.    * Walk the list of installed items and determine what the visible list is,
  7998.    * based on which items are visible at the highest priority locations.
  7999.    */
  8000.   _buildVisibleItemList: function() {
  8001.     var ctr = getContainer(this, this._itemRoot);
  8002.     var items = ctr.GetElements();
  8003.     while (items.hasMoreElements()) {
  8004.       var item = items.getNext().QueryInterface(Ci.nsIRDFResource);
  8005.       // Resource URIs adopt the format: location-key,item-id
  8006.       var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8007.       this.visibleItems[id] = this.getItemProperty(id, "installLocation");
  8008.     }
  8009.   },
  8010.  
  8011.   /**
  8012.    * Updates an item's location in the visible item list.
  8013.    * @param   id
  8014.    *          The GUID of the item to update
  8015.    * @param   locationKey
  8016.    *          The name of the Install Location where the item is installed.
  8017.    * @param   forceReplace
  8018.    *          true if the new location should be used, regardless of its
  8019.    *          priority relationship to existing entries, false if the location
  8020.    *          should only be updated if its priority is lower than the existing
  8021.    *          value.
  8022.    */
  8023.   updateVisibleList: function(id, locationKey, forceReplace) {
  8024.     if (id in this.visibleItems && this.visibleItems[id]) {
  8025.       var oldLocation = InstallLocations.get(this.visibleItems[id]);
  8026.       var newLocation = InstallLocations.get(locationKey);
  8027.       if (forceReplace || !oldLocation || newLocation.priority < oldLocation.priority)
  8028.         this.visibleItems[id] = locationKey;
  8029.     }
  8030.     else
  8031.       this.visibleItems[id] = locationKey;
  8032.   },
  8033.  
  8034.   /**
  8035.    * Load the Extensions Datasource from disk.
  8036.    */
  8037.   loadExtensions: function() {
  8038.     var extensionsFile  = getFile(KEY_PROFILEDIR, [FILE_EXTENSIONS]);
  8039.     try {
  8040.       this._inner = gRDF.GetDataSourceBlocking(getURLSpecFromFile(extensionsFile));
  8041.     }
  8042.     catch (e) {
  8043.       ERROR("Datasource::loadExtensions: removing corrupted extensions datasource " +
  8044.             " file = " + extensionsFile.path + ", exception = " + e + "\n");
  8045.       extensionsFile.remove(false);
  8046.       return;
  8047.     }
  8048.  
  8049.     var cu = Cc["@mozilla.org/rdf/container-utils;1"].
  8050.              getService(Ci.nsIRDFContainerUtils);
  8051.     cu.MakeSeq(this._inner, this._itemRoot);
  8052.  
  8053.     this._buildVisibleItemList();
  8054.   },
  8055.  
  8056.   /**
  8057.    * See nsIExtensionManager.idl
  8058.    */
  8059.   onUpdateStarted: function() {
  8060.     LOG("Datasource: Update Started");
  8061.   },
  8062.  
  8063.   /**
  8064.    * See nsIExtensionManager.idl
  8065.    */
  8066.   onUpdateEnded: function() {
  8067.     LOG("Datasource: Update Ended");
  8068.   },
  8069.  
  8070.   /**
  8071.    * See nsIExtensionManager.idl
  8072.    */
  8073.   onAddonUpdateStarted: function(addon) {
  8074.     if (!addon)
  8075.       throw Cr.NS_ERROR_INVALID_ARG;
  8076.  
  8077.     LOG("Datasource: Addon Update Started: " + addon.id);
  8078.     this.updateProperty(addon.id, "availableUpdateURL");
  8079.   },
  8080.  
  8081.   /**
  8082.    * See nsIExtensionManager.idl
  8083.    */
  8084.   onAddonUpdateEnded: function(addon, status) {
  8085.     if (!addon)
  8086.       throw Cr.NS_ERROR_INVALID_ARG;
  8087.  
  8088.     LOG("Datasource: Addon Update Ended: " + addon.id + ", status: " + status);
  8089.     var url = null, hash = null, version = null;
  8090.     var updateAvailable = status == Ci.nsIAddonUpdateCheckListener.STATUS_UPDATE;
  8091.     if (updateAvailable) {
  8092.       url = EM_L(addon.xpiURL);
  8093.       if (addon.xpiHash)
  8094.         hash = EM_L(addon.xpiHash);
  8095.       version = EM_L(addon.version);
  8096.     }
  8097.     this.setItemProperty(addon.id, EM_R("availableUpdateURL"), url);
  8098.     this.setItemProperty(addon.id, EM_R("availableUpdateHash"), hash);
  8099.     this.setItemProperty(addon.id, EM_R("availableUpdateVersion"), version);
  8100.     this.updateProperty(addon.id, "availableUpdateURL");
  8101.   },
  8102.  
  8103.   /////////////////////////////////////////////////////////////////////////////
  8104.   // nsIRDFDataSource
  8105.   get URI() {
  8106.     return "rdf:extensions";
  8107.   },
  8108.  
  8109.   GetSource: function(property, target, truthValue) {
  8110.     return this._inner.GetSource(property, target, truthValue);
  8111.   },
  8112.  
  8113.   GetSources: function(property, target, truthValue) {
  8114.     return this._inner.GetSources(property, target, truthValue);
  8115.   },
  8116.  
  8117.   /**
  8118.    * Gets an URL to a theme's image file
  8119.    * @param   item
  8120.    *          The RDF Resource representing the item
  8121.    * @param   fileName
  8122.    *          The file to locate a URL for
  8123.    * @param   fallbackURL
  8124.    *          If the location fails, supply this URL instead
  8125.    * @returns An RDF Resource to the URL discovered, or the fallback
  8126.    *          if the discovery failed.
  8127.    */
  8128.   _getThemeImageURL: function(item, fileName, fallbackURL) {
  8129.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8130.     var installLocation = this._em.getInstallLocation(id);
  8131.     if (!installLocation)
  8132.       return fallbackURL;
  8133.     var file = installLocation.getItemFile(id, fileName)
  8134.     if (file.exists())
  8135.       return gRDF.GetResource(getURLSpecFromFile(file));
  8136.  
  8137.     if (id == stripPrefix(RDFURI_DEFAULT_THEME, PREFIX_ITEM_URI)) {
  8138.       var jarFile = getFile(KEY_APPDIR, [DIR_CHROME, FILE_DEFAULT_THEME_JAR]);
  8139.       var url = "jar:" + getURLSpecFromFile(jarFile) + "!/" + fileName;
  8140.       return gRDF.GetResource(url);
  8141.     }
  8142.  
  8143.     return fallbackURL ? gRDF.GetResource(fallbackURL) : null;
  8144.   },
  8145.  
  8146.   /**
  8147.    * Get the em:iconURL property (icon url of the item)
  8148.    */
  8149.   _rdfGet_iconURL: function(item, property) {
  8150.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8151.     var type = this.getItemProperty(id, "type");
  8152.     if (type & Ci.nsIUpdateItem.TYPE_THEME)
  8153.       return this._getThemeImageURL(item, "icon.png", URI_GENERIC_ICON_THEME);
  8154.  
  8155.     if (inSafeMode())
  8156.       return gRDF.GetResource(URI_GENERIC_ICON_XPINSTALL);
  8157.  
  8158.     var hasIconURL = this._inner.hasArcOut(item, property);
  8159.     // If the addon doesn't have an IconURL property or it is disabled use the
  8160.     // generic icon URL instead.
  8161.     if (!hasIconURL || this.getItemProperty(id, "isDisabled") == "true")
  8162.       return gRDF.GetResource(URI_GENERIC_ICON_XPINSTALL);
  8163.     var iconURL = stringData(this._inner.GetTarget(item, property, true));
  8164.     try {
  8165.       var uri = newURI(iconURL);
  8166.       var scheme = uri.scheme;
  8167.       // Only allow chrome URIs or when installing http(s) URIs.
  8168.       if (scheme == "chrome" || (scheme == "http" || scheme == "https") &&
  8169.           this._inner.hasArcOut(item, EM_R("downloadURL")))
  8170.         return null;
  8171.     }
  8172.     catch (e) {
  8173.     }
  8174.     // Use a generic icon URL for addons that have an invalid iconURL.
  8175.     return gRDF.GetResource(URI_GENERIC_ICON_XPINSTALL);
  8176.   },
  8177.  
  8178.   /**
  8179.    * Get the em:previewImage property (preview image of the item)
  8180.    */
  8181.   _rdfGet_previewImage: function(item, property) {
  8182.     var type = this.getItemProperty(stripPrefix(item.Value, PREFIX_ITEM_URI), "type");
  8183.     if (type != -1 && type & Ci.nsIUpdateItem.TYPE_THEME)
  8184.       return this._getThemeImageURL(item, "preview.png", null);
  8185.     return null;
  8186.   },
  8187.  
  8188.   /**
  8189.    * If we're in safe mode, the item is disabled by the user or app, or the
  8190.    * item is to be upgraded force the generic about dialog for the item.
  8191.    */
  8192.   _rdfGet_aboutURL: function(item, property) {
  8193.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8194.     if (inSafeMode() || this.getItemProperty(id, "isDisabled") == "true" ||
  8195.         this.getItemProperty(id, "opType") == OP_NEEDS_UPGRADE)
  8196.       return EM_L("");
  8197.  
  8198.     return null;
  8199.   },
  8200.  
  8201.   _rdfGet_installDate: function(item, property) {
  8202.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8203.     var key = this.getItemProperty(id, "installLocation");
  8204.     if (key && key in StartupCache.entries && id in StartupCache.entries[key] &&
  8205.         StartupCache.entries[key][id] && StartupCache.entries[key][id].mtime)
  8206.       return EM_D(StartupCache.entries[key][id].mtime * 1000000);
  8207.     return null;
  8208.   },
  8209.  
  8210.   /**
  8211.    * Get the em:compatible property (whether or not this item is compatible)
  8212.    */
  8213.   _rdfGet_compatible: function(item, property) {
  8214.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8215.     var targetAppInfo = this.getTargetApplicationInfo(id, this);
  8216.     if (!targetAppInfo) {
  8217.       // When installing a new addon targetAppInfo does not exist yet
  8218.       if (this.getItemProperty(id, "opType") == OP_NEEDS_INSTALL)
  8219.         return EM_L("true");
  8220.       return EM_L("false");
  8221.     }
  8222.  
  8223.     getVersionChecker();
  8224.     var appVersion = targetAppInfo.appID == TOOLKIT_ID ? gApp.platformVersion : gApp.version;
  8225.     if (gVersionChecker.compare(targetAppInfo.maxVersion, appVersion) < 0 ||
  8226.         gVersionChecker.compare(appVersion, targetAppInfo.minVersion) < 0) {
  8227.       // OK, this item is incompatible.
  8228.       return EM_L("false");
  8229.     }
  8230.     return EM_L("true");
  8231.   },
  8232.  
  8233.   /**
  8234.    * Get the providesUpdatesSecurely property (whether or not this item has a
  8235.    * secure update mechanism)
  8236.    */
  8237.   _rdfGet_providesUpdatesSecurely: function(item, property) {
  8238.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8239.     if (this.getItemProperty(id, "updateKey") ||
  8240.         !this.getItemProperty(id, "updateURL") ||
  8241.         this.getItemProperty(id, "updateURL").substring(0, 6) == "https:")
  8242.       return EM_L("true");
  8243.     return EM_L("false");
  8244.   },
  8245.  
  8246.   /**
  8247.    * Get the em:blocklisted property (whether or not this item is blocklisted)
  8248.    */
  8249.   _rdfGet_blocklisted: function(item, property) {
  8250.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8251.     var version = this.getItemProperty(id, "version");
  8252.     if (!gBlocklist)
  8253.       gBlocklist = Cc["@mozilla.org/extensions/blocklist;1"].
  8254.                    getService(Ci.nsIBlocklistService);
  8255.     if (gBlocklist.isAddonBlocklisted(id, version, null, null))
  8256.       return EM_L("true");
  8257.  
  8258.     return EM_L("false");
  8259.   },
  8260.  
  8261.   /**
  8262.    * Get the em:state property (represents the current phase of an install).
  8263.    */
  8264.   _rdfGet_state: function(item, property) {
  8265.     var id = item.Value;
  8266.     if (id in this._progressData)
  8267.       return EM_L(this._progressData[id].state);
  8268.     return null;
  8269.   },
  8270.  
  8271.   /**
  8272.    * Get the em:progress property from the _progressData js object. By storing
  8273.    * progress which is updated repeastedly during a download we avoid
  8274.    * repeastedly writing it to the rdf file.
  8275.    */
  8276.   _rdfGet_progress: function(item, property) {
  8277.     var id = item.Value;
  8278.     if (id in this._progressData)
  8279.       return EM_I(this._progressData[id].progress);
  8280.     return null;
  8281.   },
  8282.  
  8283.   /**
  8284.    * Get the em:appManaged property. This prevents extensions from hiding
  8285.    * extensions installed into locations other than the app-global location.
  8286.    */
  8287.   _rdfGet_appManaged: function(item, property) {
  8288.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8289.     var locationKey = this.getItemProperty(id, "installLocation");
  8290.     if (locationKey != KEY_APP_GLOBAL)
  8291.       return EM_L("false");
  8292.     return null;
  8293.   },
  8294.  
  8295.   /**
  8296.    * Get the em:hidden property. This prevents extensions from hiding
  8297.    * extensions installed into locations other than restricted locations.
  8298.    */
  8299.   _rdfGet_hidden: function(item, property) {
  8300.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8301.     var installLocation = InstallLocations.get(this.getInstallLocationKey(id));
  8302.     if (!installLocation || !installLocation.restricted)
  8303.       return EM_L("false");
  8304.     return null;
  8305.   },
  8306.  
  8307.   /**
  8308.    * Get the em:locked property. This prevents extensions from locking
  8309.    * extensions installed into locations other than restricted locations.
  8310.    */
  8311.   _rdfGet_locked: function(item, property) {
  8312.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8313.     var installLocation = InstallLocations.get(this.getInstallLocationKey(id));
  8314.     if (!installLocation || !installLocation.restricted)
  8315.       return EM_L("false");
  8316.     return null;
  8317.   },
  8318.  
  8319.   /**
  8320.    * Get the em:satisfiesDependencies property - literal string "false" for
  8321.    * dependencies not satisfied (e.g. dependency disabled, incorrect version,
  8322.    * not installed etc.), and literal string "true" for dependencies satisfied.
  8323.    */
  8324.   _rdfGet_satisfiesDependencies: function(item, property) {
  8325.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8326.     if (this.satisfiesDependencies(id))
  8327.       return EM_L("true");
  8328.     return EM_L("false");
  8329.   },
  8330.  
  8331.   /**
  8332.    * Get the em:opType property (controls widget state for the EM UI)
  8333.    * from the Startup Cache (e.g. extensions.cache)
  8334.    */
  8335.   _rdfGet_opType: function(item, property) {
  8336.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8337.     var key = this.getItemProperty(id, "installLocation");
  8338.     if (key in StartupCache.entries && id in StartupCache.entries[key] &&
  8339.         StartupCache.entries[key][id] && StartupCache.entries[key][id].op != OP_NONE)
  8340.       return EM_L(StartupCache.entries[key][id].op);
  8341.     return null;
  8342.   },
  8343.  
  8344.   /**
  8345.    * Gets a localizable property. Install Manifests are generally only in one
  8346.    * language, however an item can customize by providing localized prefs in
  8347.    * the form:
  8348.    *
  8349.    *    extensions.{GUID}.[name|description|creator|homepageURL]
  8350.    *
  8351.    * to specify localized text for each of these properties.
  8352.    */
  8353.   _getLocalizablePropertyValue: function(item, property) {
  8354.     // These are localizable properties that a language pack supplied by the
  8355.     // Extension may override.
  8356.     var prefName = PREF_EM_EXTENSION_FORMAT.replace(/%UUID%/,
  8357.                     stripPrefix(item.Value, PREFIX_ITEM_URI)) +
  8358.                     stripPrefix(property.Value, PREFIX_NS_EM);
  8359.     try {
  8360.       var value = gPref.getComplexValue(prefName,
  8361.                                         Ci.nsIPrefLocalizedString);
  8362.       if (value.data)
  8363.         return EM_L(value.data);
  8364.     }
  8365.     catch (e) {
  8366.     }
  8367.  
  8368.     var localized = findClosestLocalizedResource(this._inner, item);
  8369.     if (localized) {
  8370.       var value = this._inner.GetTarget(localized, property, true);
  8371.       return value ? value : EM_L("");
  8372.     }
  8373.     return null;
  8374.   },
  8375.  
  8376.   /**
  8377.    * Get the em:name property (name of the item)
  8378.    */
  8379.   _rdfGet_name: function(item, property) {
  8380.     return this._getLocalizablePropertyValue(item, property);
  8381.   },
  8382.  
  8383.   /**
  8384.    * Get the em:description property (description of the item)
  8385.    */
  8386.   _rdfGet_description: function(item, property) {
  8387.     return this._getLocalizablePropertyValue(item, property);
  8388.   },
  8389.  
  8390.   /**
  8391.    * Get the em:creator property (creator of the item)
  8392.    */
  8393.   _rdfGet_creator: function(item, property) {
  8394.     return this._getLocalizablePropertyValue(item, property);
  8395.   },
  8396.  
  8397.   /**
  8398.    * Get the em:homepageURL property (homepage URL of the item)
  8399.    */
  8400.   _rdfGet_homepageURL: function(item, property) {
  8401.     return this._getLocalizablePropertyValue(item, property);
  8402.   },
  8403.   
  8404.   _rdfGet_availableUpdateInfo: function(item, property) {
  8405.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8406.     var uri = stringData(this._inner.GetTarget(item, EM_R("availableUpdateInfo"), true));
  8407.     if (uri) {
  8408.       uri = escapeAddonURI(this.getItemForID(id), uri, this);
  8409.       return EM_L(uri);
  8410.     }
  8411.     return null;
  8412.   },
  8413.  
  8414.   /**
  8415.    * Get the em:isDisabled property. This will be true if the item has a
  8416.    * appDisabled or a userDisabled property that is true or OP_NEEDS_ENABLE.
  8417.    */
  8418.   _rdfGet_isDisabled: function(item, property) {
  8419.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8420.     if (this.getItemProperty(id, "userDisabled") == "true" ||
  8421.         this.getItemProperty(id, "appDisabled") == "true" ||
  8422.         this.getItemProperty(id, "userDisabled") == OP_NEEDS_ENABLE ||
  8423.         this.getItemProperty(id, "appDisabled") == OP_NEEDS_ENABLE)
  8424.       return EM_L("true");
  8425.     return EM_L("false");
  8426.   },
  8427.  
  8428.   _rdfGet_addonID: function(item, property) {
  8429.     var id = this._inner.GetTarget(item, EM_R("downloadURL"), true) ? item.Value :
  8430.                                                                       stripPrefix(item.Value, PREFIX_ITEM_URI);
  8431.     return EM_L(id);
  8432.   },
  8433.  
  8434.   /**
  8435.    * Get the em:updateable property - this specifies whether the item is
  8436.    * allowed to be updated
  8437.    */
  8438.   _rdfGet_updateable: function(item, property) {
  8439.     var id = stripPrefix(item.Value, PREFIX_ITEM_URI);
  8440.     var opType = this.getItemProperty(id, "opType");
  8441.     if (opType != OP_NONE || this.getItemProperty(id, "appManaged") == "true")
  8442.       return EM_L("false");
  8443.  
  8444.     if (getPref("getBoolPref", (PREF_EM_ITEM_UPDATE_ENABLED.replace(/%UUID%/, id), false)) == true)
  8445.       return EM_L("false");
  8446.  
  8447.     var installLocation = InstallLocations.get(this.getInstallLocationKey(id));
  8448.     if (!installLocation || !installLocation.canAccess)
  8449.       return EM_L("false");
  8450.  
  8451.     return EM_L("true");
  8452.   },
  8453.  
  8454.   /**
  8455.    * See nsIRDFDataSource.idl
  8456.    */
  8457.   GetTarget: function(source, property, truthValue) {
  8458.     if (!source)
  8459.       return null;
  8460.  
  8461.     var target = null;
  8462.     var getter = "_rdfGet_" + stripPrefix(property.Value, PREFIX_NS_EM);
  8463.     if (getter in this)
  8464.       target = this[getter](source, property);
  8465.  
  8466.     return target || this._inner.GetTarget(source, property, truthValue);
  8467.   },
  8468.  
  8469.   /**
  8470.    * Gets an enumeration of values of a localizable property. Install Manifests
  8471.    * are generally only in one language, however an item can customize by
  8472.    * providing localized prefs in the form:
  8473.    *
  8474.    *    extensions.{GUID}.[contributor].1
  8475.    *    extensions.{GUID}.[contributor].2
  8476.    *    extensions.{GUID}.[contributor].3
  8477.    *    ...
  8478.    *
  8479.    * to specify localized text for each of these properties.
  8480.    */
  8481.   _getLocalizablePropertyValues: function(item, property) {
  8482.     // These are localizable properties that a language pack supplied by the
  8483.     // Extension may override.
  8484.     var values = [];
  8485.     var prefName = PREF_EM_EXTENSION_FORMAT.replace(/%UUID%/,
  8486.                     stripPrefix(item.Value, PREFIX_ITEM_URI)) +
  8487.                     stripPrefix(property.Value, PREFIX_NS_EM);
  8488.     var i = 0;
  8489.     while (true) {
  8490.       try {
  8491.         var value = gPref.getComplexValue(prefName + "." + ++i,
  8492.                                           Ci.nsIPrefLocalizedString);
  8493.         if (value.data)
  8494.           values.push(EM_L(value.data));
  8495.       }
  8496.       catch (e) {
  8497.         try {
  8498.           var value = gPref.getComplexValue(prefName,
  8499.                                             Ci.nsIPrefLocalizedString);
  8500.           if (value.data)
  8501.             values.push(EM_L(value.data));
  8502.         }
  8503.         catch (e) {
  8504.         }
  8505.         break;
  8506.       }
  8507.     }
  8508.     if (values.length > 0)
  8509.       return values;
  8510.  
  8511.     var localized = findClosestLocalizedResource(this._inner, item);
  8512.     if (localized) {
  8513.       var targets = this._inner.GetTargets(localized, property, true);
  8514.       while (targets.hasMoreElements())
  8515.         values.push(targets.getNext());
  8516.       return values;
  8517.     }
  8518.     return null;
  8519.   },
  8520.  
  8521.   /**
  8522.    * Get the em:developer property (developers of the extension)
  8523.    */
  8524.   _rdfGets_developer: function(item, property) {
  8525.     return this._getLocalizablePropertyValues(item, property);
  8526.   },
  8527.  
  8528.   /**
  8529.    * Get the em:translator property (translators of the extension)
  8530.    */
  8531.   _rdfGets_translator: function(item, property) {
  8532.     return this._getLocalizablePropertyValues(item, property);
  8533.   },
  8534.  
  8535.   /**
  8536.    * Get the em:contributor property (contributors to the extension)
  8537.    */
  8538.   _rdfGets_contributor: function(item, property) {
  8539.     return this._getLocalizablePropertyValues(item, property);
  8540.   },
  8541.  
  8542.   /**
  8543.    * See nsIRDFDataSource.idl
  8544.    */
  8545.   GetTargets: function(source, property, truthValue) {
  8546.     if (!source)
  8547.       return null;
  8548.  
  8549.     var ary = null;
  8550.     var propertyName = stripPrefix(property.Value, PREFIX_NS_EM);
  8551.     var getter = "_rdfGets_" + propertyName;
  8552.     if (getter in this)
  8553.       ary = this[getter](source, property);
  8554.     else {
  8555.       // The template builder calls GetTargets when single value properties
  8556.       // are used in a triple.
  8557.       getter = "_rdfGet_" + propertyName;
  8558.       if (getter in this)
  8559.         ary = [ this[getter](source, property) ];
  8560.     }
  8561.  
  8562.     return ary ? new ArrayEnumerator(ary)
  8563.                : this._inner.GetTargets(source, property, truthValue);
  8564.   },
  8565.  
  8566.   Assert: function(source, property, target, truthValue) {
  8567.     this._inner.Assert(source, property, target, truthValue);
  8568.   },
  8569.  
  8570.   Unassert: function(source, property, target) {
  8571.     this._inner.Unassert(source, property, target);
  8572.   },
  8573.  
  8574.   Change: function(source, property, oldTarget, newTarget) {
  8575.     this._inner.Change(source, property, oldTarget, newTarget);
  8576.   },
  8577.  
  8578.   Move: function(oldSource, newSource, property, target) {
  8579.     this._inner.Move(oldSource, newSource, property, target);
  8580.   },
  8581.  
  8582.   HasAssertion: function(source, property, target, truthValue) {
  8583.     if (!source || !property || !target)
  8584.       return false;
  8585.  
  8586.     var getter = "_rdfGet_" + stripPrefix(property.Value, PREFIX_NS_EM);
  8587.     if (getter in this)
  8588.       return this[getter](source, property) == target;
  8589.     return this._inner.HasAssertion(source, property, target, truthValue);
  8590.   },
  8591.  
  8592.   _observers: [],
  8593.   AddObserver: function(observer) {
  8594.     for (var i = 0; i < this._observers.length; ++i) {
  8595.       if (this._observers[i] == observer)
  8596.         return;
  8597.     }
  8598.     this._observers.push(observer);
  8599.     this._inner.AddObserver(observer);
  8600.   },
  8601.  
  8602.   RemoveObserver: function(observer) {
  8603.     for (var i = 0; i < this._observers.length; ++i) {
  8604.       if (this._observers[i] == observer)
  8605.         this._observers.splice(i, 1);
  8606.     }
  8607.     this._inner.RemoveObserver(observer);
  8608.   },
  8609.  
  8610.   ArcLabelsIn: function(node) {
  8611.     return this._inner.ArcLabelsIn(node);
  8612.   },
  8613.  
  8614.   ArcLabelsOut: function(source) {
  8615.     return this._inner.ArcLabelsOut(source);
  8616.   },
  8617.  
  8618.   GetAllResources: function() {
  8619.     return this._inner.GetAllResources();
  8620.   },
  8621.  
  8622.   IsCommandEnabled: function(sources, command, arguments) {
  8623.     return this._inner.IsCommandEnabled(sources, command, arguments);
  8624.   },
  8625.  
  8626.   DoCommand: function(sources, command, arguments) {
  8627.     this._inner.DoCommand(sources, command, arguments);
  8628.   },
  8629.  
  8630.   GetAllCmds: function(source) {
  8631.     return this._inner.GetAllCmds(source);
  8632.   },
  8633.  
  8634.   hasArcIn: function(node, arc) {
  8635.     return this._inner.hasArcIn(node, arc);
  8636.   },
  8637.  
  8638.   hasArcOut: function(source, arc) {
  8639.     return this._inner.hasArcOut(source, arc);
  8640.   },
  8641.  
  8642.   beginUpdateBatch: function() {
  8643.     return this._inner.beginUpdateBatch();
  8644.   },
  8645.  
  8646.   endUpdateBatch: function() {
  8647.     return this._inner.endUpdateBatch();
  8648.   },
  8649.  
  8650.   /**
  8651.    * See nsIRDFRemoteDataSource.idl
  8652.    */
  8653.   get loaded() {
  8654.     throw Cr.NS_ERROR_NOT_IMPLEMENTED;
  8655.   },
  8656.  
  8657.   Init: function(uri) {
  8658.   },
  8659.  
  8660.   Refresh: function(blocking) {
  8661.   },
  8662.  
  8663.   Flush: function() {
  8664.     if (this._inner instanceof Ci.nsIRDFRemoteDataSource)
  8665.       this._inner.Flush();
  8666.   },
  8667.  
  8668.   FlushTo: function(uri) {
  8669.   },
  8670.  
  8671.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIRDFDataSource,
  8672.                                          Ci.nsIRDFRemoteDataSource])
  8673. };
  8674.  
  8675. function UpdateItem () {}
  8676. UpdateItem.prototype = {
  8677.   /**
  8678.    * See nsIUpdateService.idl
  8679.    */
  8680.   init: function(id, version, installLocationKey, minAppVersion, maxAppVersion,
  8681.                  name, downloadURL, xpiHash, iconURL, updateURL, updateKey, type,
  8682.                  targetAppID) {
  8683.     this._id                  = id;
  8684.     this._version             = version;
  8685.     this._installLocationKey  = installLocationKey;
  8686.     this._minAppVersion       = minAppVersion;
  8687.     this._maxAppVersion       = maxAppVersion;
  8688.     this._name                = name;
  8689.     this._downloadURL         = downloadURL;
  8690.     this._xpiHash             = xpiHash;
  8691.     this._iconURL             = iconURL;
  8692.     this._updateURL           = updateURL;
  8693.     this._updateKey           = updateKey;
  8694.     this._type                = type;
  8695.     this._targetAppID         = targetAppID;
  8696.   },
  8697.  
  8698.   /**
  8699.    * See nsIUpdateService.idl
  8700.    */
  8701.   get id()                { return this._id;                },
  8702.   get version()           { return this._version;           },
  8703.   get installLocationKey(){ return this._installLocationKey;},
  8704.   get minAppVersion()     { return this._minAppVersion;     },
  8705.   get maxAppVersion()     { return this._maxAppVersion;     },
  8706.   get name()              { return this._name;              },
  8707.   get xpiURL()            { return this._downloadURL;       },
  8708.   get xpiHash()           { return this._xpiHash;           },
  8709.   get iconURL()           { return this._iconURL            },
  8710.   get updateRDF()         { return this._updateURL;         },
  8711.   get updateKey()         { return this._updateKey;         },
  8712.   get type()              { return this._type;              },
  8713.   get targetAppID()       { return this._targetAppID;       },
  8714.  
  8715.   /**
  8716.    * See nsIUpdateService.idl
  8717.    */
  8718.   get objectSource() {
  8719.     return { id                 : this._id,
  8720.              version            : this._version,
  8721.              installLocationKey : this._installLocationKey,
  8722.              minAppVersion      : this._minAppVersion,
  8723.              maxAppVersion      : this._maxAppVersion,
  8724.              name               : this._name,
  8725.              xpiURL             : this._downloadURL,
  8726.              xpiHash            : this._xpiHash,
  8727.              iconURL            : this._iconURL,
  8728.              updateRDF          : this._updateURL,
  8729.              updateKey          : this._updateKey,
  8730.              type               : this._type,
  8731.              targetAppID        : this._targetAppID
  8732.            }.toSource();
  8733.   },
  8734.  
  8735.   classDescription: "Update Item",
  8736.   contractID: "@mozilla.org/updates/item;1",
  8737.   classID: Components.ID("{F3294B1C-89F4-46F8-98A0-44E1EAE92518}"),
  8738.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIUpdateItem])
  8739. };
  8740.  
  8741. var gEmSingleton = null;
  8742. var EmFactory = {
  8743.   createInstance: function(outer, iid) {
  8744.     if (outer != null)
  8745.       throw Cr.NS_ERROR_NO_AGGREGATION;
  8746.  
  8747.     if (!gEmSingleton)
  8748.       gEmSingleton = new ExtensionManager();
  8749.     return gEmSingleton.QueryInterface(iid);
  8750.   }
  8751. };
  8752.  
  8753. function DatasourceModule() {}
  8754. DatasourceModule.prototype = {
  8755.   classDescription: "Extension Manager Data Source",
  8756.   contractID: "@mozilla.org/rdf/datasource;1?name=extensions",
  8757.   classID: Components.ID("{69BB8313-2D4F-45EC-97E0-D39DA58ECCE9}"),
  8758.   _xpcom_factory: {
  8759.     createInstance: function() Cc[ExtensionManager.prototype.contractID].
  8760.                                getService(Ci.nsIExtensionManager).datasource
  8761.   }
  8762. };
  8763.  
  8764.  
  8765. function NSGetModule(compMgr, fileSpec)
  8766.   XPCOMUtils.generateModule([ExtensionManager, DatasourceModule, UpdateItem]);
  8767.  
  8768.